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