Question

I want to do something like this:

@property (nonatomic, retain) NSObject *obj1;
@property (nonatomic, retain) NSObject *obj2;

- (id)init {

    if ((self = [super init])) {

        [SomeClass someFuncWithParam1:*(self.obj1) param2:*(self.obj2)];
    }
}

@implementation SomeClass
+ (void)someFuncWithParam1:(NSObject **)param1 param2:(NSObject **)param2 {

    //init obj1;
    ...
    //init obj2;
    ...
}
@end

I haven't found any example how to pass objective-C properties into a function for initialization. I know that it is possible with usual variables but there are no examples about what to do with properties.

Was it helpful?

Solution

You cannot pass an argument by reference in (Objective-)C. What you probably mean is to pass the address of a variable as an argument to the method, so that the method can set the value of the variable via the pointer.

However, this does not work with properties. self.obj1 is just a convenient notation for the method call [self obj1], which returns the value of the property. And taking the address of a return value is not possible.

What you can do is

  • Pass the address of the corresponding instance variables:

    [SomeClass someFuncWithParam1:&_obj1 param2:&_obj2];
    

    The disadvantage is that the property accessor methods are bypassed. That may or may not be relevant in your case.

  • Pass the address of temporary local variables:

    NSObject *tmpObj1;
    NSObject *tmpObj2;
    [SomeClass someFuncWithParam1:&tmpObj1 param2:&tmpObj2];
    self.obj1 = tmpObj1;
    self.obj2 = tmpObj2;
    

Both solutions are not very nice. Alternatively, you could pass the entire object (self) to the helper method, which then initializes both properties.

Or you define a custom class with just the properties obj1 and obj2, and make the helper method return an instance of this custom class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top