Objective-C:将属性引用传递给方法调用的正确方法

标签 objective-c ios macos cocoa

如果我有这样的属性:

@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/

相关文章:

ios - 将 UIImageView 与自动布局对齐

ios - 缓存蓝牙连接 iOS

iphone - 在 Objective-C 中搜索字符串的最快方法是什么?

ios - 如何在 Objective c 中动态设置 UILabel 高度?

MySQL安装错误

c - 使用 CalcOpticalFlowFarneback 函数构建错误 -> OpenCV -> C 语言 - Eclipse -> MacOSX

iphone - uialertview 中按钮的属性启用

ios - Xcode 方案的 "analyze"部分中的 "test"、 "Build"和其他复选框是什么?

ios - 在 iOS 8 中推送/弹出 View 时显示/隐藏导航栏

javascript - 如何从 safari 中仅隐藏画中画 (PiP) 控件