Objective-C copy and retain
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.
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.
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.