When should I use copy instead of using retain? I didn't quite get it.
-
possible duplicate of [NSString property: copy or retain?](http://stackoverflow.com/questions/387959/nsstring-property-copy-or-retain) or [Objective C Assign Copy Retain](http://stackoverflow.com/questions/4510913/) or [Retain Copy of autoreleased objects](http://stackoverflow.com/questions/6416963/) or [When to use retain and when to use copy](http://stackoverflow.com/questions/4087208/) or [@property: Retain or copy?](http://stackoverflow.com/questions/5616170/) or [many others](http://stackoverflow.com/search?q=%5Bobjc%5D+copy+retain) – jscs Jun 22 '11 at 18:16
-
In this questions defense, the others are all specific to property types, but yes, this question has been asked a lot. – Joshua Weinberg Jun 22 '11 at 20:04
3 Answers
You would use copy
when you want to guarantee the state of the object.
NSMutableString *mutString = [NSMutableString stringWithString:@"ABC"];
NSString *b = [mutString retain];
[mutString appendString:@"Test"];
At this point b was just messed up by the 3rd line there.
NSMutableString *mutString = [NSMutableString stringWithString:@"ABC"];
NSString *b = [mutString copy];
[mutString appendString:@"Test"];
In this case b is the original string, and isn't modified by the 3rd line.
This applies for all mutable types.

- 28,598
- 2
- 97
- 90
-
4It's worth noting that many immutable types will implement -copy by calling -retain; Since their value will never change, there's no point in having two copies in memory. That said, absent futher info, you should always code as if you don't know whether a particular object is mutable or not. Just because you type your property as NSString doesn't mean someone won't pass an NSMutableString to it (as illustrated above.) – ipmcc Jun 22 '11 at 20:05
retain : It is done on the created object, and it just increase the reference count.
copy -- It creates a new object and when new object is created retain count will be 1. Hope this may help you.

- 407
- 1
- 7
- 16
-
-
so in retain we increase the reference count onto the same object, while for copy we increase the reference count on a new object? – mfaani Apr 08 '16 at 14:08
Copy is useful when you do not want the value that you receive to get changed without you knowing. For example if you have a property that is an NSString
and you rely on that string not changing once it is set then you need to use copy. Otherwise someone can pass you an NSMutableString
and change the value which will in turn change the underlying value of your NSString
. The same thing goes with an NSArray
and NSMutableArray
except copy on an array just copies all the pointer references to a new array but will prevent entries from being removed and added.

- 56,979
- 9
- 128
- 135