NSString @property,使用copy而不是retain [英] NSString @property, using copy instead of retain
问题描述
我正在查看苹果的示例应用程序EditableDetailView,并注意到,在他们的控制器中,他们正在设置一个NSString属性的实例(非原子,复制)。什么时候使用copy而不是retain?是这样,所以他们可以在不影响现有数据的情况下创建唯一的副本?
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?
推荐答案
是的,复制而不影响现有数据。合成的安装程序本质上是这样的:
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,使用copy而不是retain的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!