如果我有这样的属性:
@property(strong, readwrite, nonatomic) NSDate* aProperty;
我想将引用传递给另一个方法,这些是否正确:
if([AnotherClass aMethod:&(self.aProperty)]) { ...
if([AnotherClass aMethod:&self.aProperty]) { ...
最佳答案
考虑你的例子:
if ([AnotherClass aMethod:&(self.aProperty)]) { ...
这显然行不通,因为点符号实际上是在使用 getter 访问器方法。它相当于:
if ([AnotherClass aMethod:&[self aProperty]]) { ...
您可以很容易地想象为什么编译器对这种表示法有点困惑。合乎逻辑的替代方法是引用 ivar。因此,(假设您对属性的 ivar 使用下划线约定)它可能看起来像:
if ([AnotherClass aMethod:&_aProperty]) { ...
但这有各种各样的问题(绕过 setter,有关于 aMethod
需要 __strong
属性来覆盖默认 __autoreleasing
的问题,如讨论的 here等)。
因此,最好的办法可能是只使用一个局部变量来接收更新,然后调用该属性的 setter :
NSDate *date;
if ([AnotherClass aMethod:&date]) { ...
self.aProperty = date;
关于Objective-C:将属性引用传递给方法调用的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12760234/