ios - 二传手不保留

标签 ios xcode

为什么我得到以下输出:

@property (nonatomic, retain) Player *thePlayer;

然后,在 .m 中:

NSLog(@"aPlayer retain count = %i",[aPlayer retainCount]);
thePlayer = aPlayer;
NSLog(@"thePlayer retain count = %i",[thePlayer retainCount]);

给出:

2012-09-18 21:52:36.787 Pocket Dungeons[56613:10a03] aPlayer retain count = 1
2012-09-18 21:52:36.788 Pocket Dungeons[56613:10a03] thePlayer retain count = 1

最佳答案

您没有使用二传手。您正在使用 ivar(实例变量)。使用 declared property 的 setter , 使用以下语法:

self.thePlayer = aPlayer;

相当于:

[self setThePlayer:aPlayer];

但是在没有对所有者对象(在本例中为 self)的引用的情况下,您将最终直接使用实例变量,并且不会调用 setter。因此,在您的原始示例中,您没有使用 setter。

顺便说一句,这就是为什么通常建议在 @synthesize 语句中使用不同的 ivar 名称,例如:

@synthesize thePlayer = _thePlayer;

这样,当您指的是属性时,您不太可能意外引用实例变量。在 Xcode 4.4 或更高版本中,如果您省略 @synthesize 语句,这是默认行为(其中合成的实例变量将具有前导下划线)。

关于ios - 二传手不保留,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12487584/

相关文章:

ios - 是否可以在视频中添加模糊效果?

objective-c - cocoa touch 调光背景变暗

cocoa-touch - 如何重命名 infoplist.strings 文件?

Swift 包管理器和 Xcode : Retaining Xcode Settings?

ios - 以编程方式将栏按钮项目图像设置为系统项目—Swift

ios - 如何在购买通知中为苹果设置测试和生产环境

ios - 如何判断 'Mobile Network Data' 在 iOS 中是启用还是禁用(即使通过 WiFi 连接)?

ios - Unity3d for iOS 下的 Json.NET

ios - UISearchBar 背景颜色不适用于最小的 searchBarStyle

ios - Rails API 的 POST 方法