objective-c - 关于保留和复制
<p><p>我以为我已经理解了 <code>retain</code> 和 <code>copy</code> 之间的区别。但是当我遇到下面的代码时,我再次感到困惑。这些是代码:</p>
<p>ViewController.h:</p>
<pre><code>#import <UIKit/UIKit.h>
@interface ViewController : UIViewController {
NSMutableString *a;
NSMutableString *b;
NSMutableString *c;
}
@property (nonatomic, copy) NSMutableString *a;
@property (nonatomic, copy) NSMutableString *b;
@property (nonatomic, copy) NSMutableString *c;
@end
</code></pre>
<p>ViewController.m:</p>
<pre><code>#import "ViewController.h"
@implementation ViewController
@synthesize a, b, c;
- (void)viewDidLoad
{
;
self.a = [ initWithFormat:@"%@", @"aaa"];
NSLog(@"a:%d", a.retainCount);
self.b = a;
NSLog(@"a:%d", a.retainCount);
NSLog(@"b:%d", b.retainCount);
self.c = b;
NSLog(@"a:%d", a.retainCount);
NSLog(@"b:%d", b.retainCount);
NSLog(@"b:%d", c.retainCount);
}
@end
</code></pre>
<p>谁能解释一下为什么会这样:</p>
<pre><code>2011-12-31 16:54:50.244 RetainCopy a:1
2011-12-31 16:54:50.246 RetainCopy a:2
2011-12-31 16:54:50.246 RetainCopy b:2
2011-12-31 16:54:50.247 RetainCopy a:3
2011-12-31 16:54:50.247 RetainCopy b:3
2011-12-31 16:54:50.248 RetainCopy b:3
</code></pre>
<p>?谢谢。</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>首先,<code>-retainCount</code> 是<a href="https://stackoverflow.com/questions/5784084/calling-retaincount-considered-harmful/5786253#5786253" rel="noreferrer noopener nofollow">useless to you</a> .</p>
<p>第二,一个误解是在复制属性的实现中。您没有像预期的那样在这里获得副本。相反,您得到的是 <code></code> 而不是 <code></code> 的结果。许多不可变类型像这样“复制”自己(简化):</p>
<pre><code>- (id)copyWithZone:(NSZone*)zone
{
return ;
}
</code></pre>
<p>所以结果最终会是:</p>
<pre><code>NSMutableString * a = [ initWithString:@"aaa"];
NSString * b = ; // << returns an immutable copy!
NSString * c = ; // << immutable to immutable probably just retains itself!
</code></pre>
<p>由于它们是不可变的和纯粹的,这在语义上是合理的。这也意味着<em>如果类型区分不可变副本和可变副本,您将需要自己实现可变类型的副本访问器</em>。否则,当您尝试改变 ivar 时,您的程序可能会崩溃,因为您持有一个不可变的实例。如果将此添加到 <code>-viewDidLoad</code> 的末尾,您应该会看到一个异常:<code>;</code></p>
<p> <a href="https://stackoverflow.com/questions/4995254/nsmutablestring-as-retain-copy/5004019#5004019" rel="noreferrer noopener nofollow">More detail on implementing a mutable property here</a> .</p></p>
<p style="font-size: 20px;">关于objective-c - 关于保留和复制,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/8687270/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/8687270/
</a>
</p>
页:
[1]