Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between "copy" and "retain"?

What is the difference between copy and retain for NSString?

- (void)setString:(NSString*)newString {     string = [newString copy]; } 
like image 657
senthilM Avatar asked Mar 08 '10 05:03

senthilM


People also ask

Does copy increase retain count?

No, a copied object will have a retain count of 1, just like a newly initialized object.

What is difference between assign and retain?

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.

What is retain in iOS?

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.

What does it mean to retain a copy?

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.


2 Answers

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 NSStrings 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.

like image 51
Malaxeur Avatar answered Sep 24 '22 23:09

Malaxeur


Retaining and copying are two different things, the first is conceptually call-by-reference while the second is call-by-value.

like image 22
iTayb Avatar answered Sep 26 '22 23:09

iTayb