NSString @property,使用复制而不是保留 [英] NSString @property, using copy instead of retain

查看:28
本文介绍了NSString @property,使用复制而不是保留的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看 Apple 的示例应用程序 EditableDetailView,并注意到在他们的一个控制器中,他们使用 (nonatomic, copy) 设置了 NSString 属性的实例.什么时候会使用副本而不是保留?这样他们就可以在不影响现有数据的情况下制作独特的副本吗?

I'm looking over Apple's sample application EditableDetailView, and noticed that in one of their controllers, they're setting an instance of NSString property with (nonatomic, copy). When would one use copy instead of retain? Is this so they can make a unique copy without affecting the existing data?

推荐答案

是的,它可以在不影响现有数据的情况下制作唯一的副本.合成的 setter 基本上如下所示:

Yes, it's so that it can make a unique copy without affecting the existing data. The synthesized setters essentially look like this:

// For @synthesize(nonatomic, retain) foo:
- (void) setFoo(NSFoo *theFoo)
{
    [theFoo retain];  // retain new value
    [foo release];    // release old value, if any
    foo = theFoo;     // assign new value
}

// For @synthesize(nonatomic, copy) foo:
- (void) setFoo(NSFoo *theFoo)
{
    NSFoo* newFoo = [theFoo copy];  // make copy
    [foo release];  // release old value, if any
    foo = newFoo;   // assign new value
}

注意这里的操作顺序很重要 - 在释放旧值之前必须保留/复制新值,以防自赋值.如果您先释放,然后将属性分配给自身,则可能会意外释放该值.另请注意,如果旧值是 nil,则向其发送 release 消息是可以的,因为明确允许向 nil 对象发送消息什么都不做.

Note the order of operations here is important - the new value must be retained/copied before the old value is released, in case of self-assignment. If you released first and then assigned the property to itself, you might deallocate the value by accident. Also note that if the old value is nil, sending it a release message is ok, since sending a message to a nil object is explicitly allowed and does nothing.

保留还是复制的选择仅决定对象的属性是否与您设置的属性共享相同的值.考虑以下代码:

The choice of retaining versus copying just determines whether or not the object's property shares the same value with what you're setting it to. Consider the following code:

// suppose the 'foo' property is declared 'retain' and the 'bar' property is
// declared 'copy'
NSFoo *foo = ...;
NSBar *bar = ...;
someObject.foo = foo;
someObject.bar = bar;
[foo changeInternalState];  // someObject.foo also changes, since it's the same object
[bar changeInternalState];  // someObject.bar does NOT change, since it's a copy

这篇关于NSString @property,使用复制而不是保留的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆