gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 17:28:06 25 4
gpt4 key购买 nike

这个问题让我有点困惑。在“.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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com