我在没有 ARC 的 XCode 6.4 下测试 copy/retain 属性。
@property(nonatomic, retain) NSMutableString *retainString;
@property(nonatomic, copy) NSMutableString *copyedString;
@synthesize copyedString, retainString;
NSMutableString *mStr = [NSMutableString stringWithFormat"abc"];
retainString = mStr;
copyedString = mStr;
NSLog(@"mStr:%p", mStr);
NSLog(@"retainStr:%p", retainString);
NSLog(@"copyStr:%p", copyedString);
[mStr appendString"de"];
NSLog(@"retainStr:%@", retainString);
NSLog(@"copyStr:%@", copyedString);
[copyedString appendString"123"];
NSLog(@"mStr:%@", mStr);
NSLog(@"copyStr:%@", copyedString);
NSLog(@"retainStr:%@", retainString);
我的问题:
copyedString 应该分配一个新空间,三个字符串的地址相同。
- 当
mString 改变时,copyedString 不应该改变(我知道它们现在是同一个地址所以改变了)
copyedString 已更改,mStr 和 retainString 不应更改。
我是不是做错了什么?
这里是日志:
[10656:986440] mStr:0x7f871bd71340
[10656:986440] retainStr:0x7f871bd71340
[10656:986440] copyStr:0x7f871bd71340
[10656:986440] retainStr:abcde
[10656:986440] copyStr:abcde
[10656:986440] mStr:abcde123
[10656:986440] copyStr:abcde123
[10656:986440] retainStr:abcde123
编辑哦,是的,我的错。 self.property 将调用 setter 和 getter,这意味着使用了副本。
所以解决办法就是把这两行改成:
self.retainString = mStr;
self.copyedString = mStr;
但是我收到了这个崩溃错误:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to mutate immutable object with appendString:'
*** First throw call stack:
copyedString 会变成 NSString 吗?
Best Answer-推荐答案 strong>
如果你想设置值,你应该使用 self 来访问复制属性。
NSMutableString *mStr = [NSMutableString stringWithFormat"abc"];
self.retainString = mStr;
self.copyedString = mStr;
NSLog(@"mStr:%p", mStr);
NSLog(@"retainStr:%p", self.retainString);
NSLog(@"copyStr:%p", self.copyedString);
[mStr appendString"de"];
NSLog(@"retainStr:%@", self.retainString);
NSLog(@"copyStr:%@", self.copyedString);
日志
2015-07-24 16:11:19.728 OCTest[13193:268356] mStr:0x7f84034ba020
2015-07-24 16:11:19.729 OCTest[13193:268356] retainStr:0x7f84034ba020
2015-07-24 16:11:19.729 OCTest[13193:268356] copyStr:0x7f84034bfa50
2015-07-24 16:11:19.729 OCTest[13193:268356] retainStr:abcde
2015-07-24 16:11:19.729 OCTest[13193:268356] copyStr:abc
以你的方式,它不是复制,它只是使用指针来访问地址。所以,它指向同一个地址
编辑
如果要复制属性返回可变结果,请删除@synthesize ,然后重写
-(void)setCopyedStringNSMutableString *)copyedString{
_copyedString = [copyedString mutableCopy];
}
关于ios - NSMutableString 保留/复制是一样的(复制不起作用?),我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/31604982/
|