Samuli Lehtonen
Samuli Lehtonen

Reputation: 3860

Objective-C copy and retain

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

Upvotes: 10

Views: 18680

Answers (3)

iPhone NewBIe
iPhone NewBIe

Reputation: 407

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.

Upvotes: 7

Joe
Joe

Reputation: 57179

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.

Upvotes: 4

Joshua Weinberg
Joshua Weinberg

Reputation: 28688

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.

Upvotes: 34

Related Questions