Objective-C copy and retain

Samuli Lehtonen picture Samuli Lehtonen · Jun 22, 2011 · Viewed 17k times · Source

When should I use copy instead of using retain? I didn't quite get it.

Answer

Joshua Weinberg picture Joshua Weinberg · Jun 22, 2011

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.