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?
I’m looking over Apple’s sample application EditableDetailView, and noticed that in one of their
Share
Yes, it’s so that it can make a unique copy without affecting the existing data. The synthesized setters essentially look like this:
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 areleasemessage is ok, since sending a message to anilobject 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: