tags:

views:

410

answers:

5

What is the difference between copy and retain for NSString?

- (void)setString:(NSString*)newString
{
        string = [newString copy];
}
+2  A: 

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

If you ask me, copy should be used for NSString. If it's Mutable, then it gets copied. If it's not, then it just gets retained. Exactly the semantics that you want in an app (let the type do what's best).

iTayb
+6  A: 

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.

Malaxeur
It should be mentioned that `copy` is equivalent to `retain` for most of the `Foundation` classes that aren't mutable.
rpetrich
A: 

The biggest difference is that if you use copy, the object you are copying must implement the NSCopying protocol (very easy to do). Not every object implements that, so you need to use care you know for sure what type you'll be operating against (or check for support of that protocol) when trying to call copy.

The best rule of thumb to using copy I can think of, is to always set NSString properties to "copy" instead of retain. That way you get more accurate readings from the Leaks instrument if you mess up and forget to release a string an object is holding onto. Other uses of copy need to be more carefully thought out.

Kendall Helmstetter Gelner
A: 

copy: creates a new instance that's a copy of the receiver. It means that you'll have 2 different

retain: Increases the retainCount of the receiver. An object is removed from memory - deadlocked, when retainCount is 0.

mxg
I think you mean "dealloc'ed" (a little awkward to verbify that word), not "deadlocked"
Brian
A: 

if you use retain, it copy the pointer value from original one.retain also increment the reference count by one. but in case of copy, it duplicate the data referenced by the pointer and assign it to copy's instance variable.