Sending property as function reference parameter in iOS?

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 did not find any example of how to pass objective-C properties to a function to initialize. I know this is possible with regular variables, but there are no examples on what to do with properties.

0
function properties objective-c parameters ref
source share
1 answer

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

However, this does not work with properties. self.obj1 is just a convenient entry for calling the [self obj1] method, which returns the value of the property. And it is impossible to accept the address of the return value.

What you can do is

  • Pass the address of the corresponding instance variables:

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

    The disadvantage is that property access methods are excluded. This may or may not be 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 pleasant. Alternatively, you can pass the entire object ( self ) to a helper method, which then initializes both properties.

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

0
source share

All Articles