Sending property as a reference param to a function in iOS?

╄→гoц情女王★ 提交于 2019-12-25 06:31:40

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/23605298/sending-property-as-a-reference-param-to-a-function-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!