What is the difference between copy
and retain
for NSString
?
- (void)setString:(NSString*)newString { string = [newString copy]; }
No, a copied object will have a retain count of 1, just like a newly initialized object.
Assign creates a reference from one object to another without increasing the source's retain count. Retain creates a reference from one object to another and increases the retain count of the source object.
You send an object a retain message when you want to prevent it from being deallocated until you have finished using it. An object is deallocated automatically when its reference count reaches 0 . retain messages increment the reference count, and release messages decrement it.
Whenever one party sends something to the other party, it retains a copy of the data it sent until the recipient has acknowledged that it received it.
In a general setting, retaining an object will increase its retain count by one. This will help keep the object in memory and prevent it from being blown away. What this means is that if you only hold a retained version of it, you share that copy with whomever passed it to you.
Copying an object, however you do it, should create another object with duplicate values. Think of this as a clone. You do NOT share the clone with whomever passed it to you.
When dealing with NSString
s in particular, you may not be able to assume that whoever is giving you an NSString
is truly giving you an NSString
. Someone could be handing you a subclass (NSMutableString
, in this case) which means that they could potentially modify the values under the covers. If your application depends on the value passed in, and someone changes it on you, you can run into trouble.
Retaining and copying are two different things, the first is conceptually call-by-reference while the second is call-by-value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With