iphone - 关于Objective c中retain和copy的问题

标签 iphone objective-c cocoa copy retain

这个问题让我有点困惑。 在“.h”文件中。

@property (nonatomic,retain) NSMutableString *str1;
@property (nonatomic,copy) NSMutableString *str2;

在“.m”文件中。

NSMutableString *testRetain = [[NSMutableString alloc] initWithString:@"prefix"];
 NSLog(@"retain count is %d",[testRetain retainCount]);
 NSLog(@"mem add is %p",testRetain);

 str1 = testRetain;
 NSLog(@"retain count is %d",[testRetain retainCount]); 
 NSLog(@"mem add is %p",testRetain);

 str2 = testRetain;
 NSLog(@"retain count is %d",[str2 retainCount]); 
 NSLog(@"mem add is %p",str2);

所有的retainCount和内存地址都是相同的。 据我所知,@property(nonatomic,retain)会添加所指向的对象的retainCount。因此,代码的第二部分应该输出与第一部分代码相同的内存地址和不同的containCount。 并且@property(nonatomic,copy)会将对象复制到新区域。因此代码的第三部分应该输出与代码第一部分不同的内存地址。 为什么我得到这个结果。 非常感谢。

最佳答案

两点。首先,也是最重要的:不要使用retainCount作为调试工具。有很多原因可能导致它无法为您提供预期的值(value)。它在文档中说了这么多。

但在这种情况下——第二点——它不起作用的原因是您直接访问变量而不是使用访问器。

而不是:

str = testRetain;

尝试:

self.str = testRetain;

关于iphone - 关于Objective c中retain和copy的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4656143/

相关文章:

swift - 没有为每个菜单项调用 validateMenuItem

iphone - 强制 UIView 立即重绘,而不是在下一个运行循环期间重绘

objective-c - 在 Swift 中使用 PDFKIT 搜索 PDF

objective-c - 使用鼠标切换 TableView 单元格的选定状态

cocoa - 无法将操作连接到 NSViewController

ios - 使用 danielgindi/ios-charts 库创建折线图

iphone - 如何在不实际缩放的情况下更改 View 缩放值?

php - 使用 AFNetworking 从 ios 中的照片库上传图像?

iphone - 如何运行另一个线程并使用该线程运行计时器来重复进程?

objective-c - 向 UIPopoverController 添加东西