James Raitsev
James Raitsev

Reputation: 96381

What is the rule of thumb for using @property(copy) vs. @property(retain)?

I wonder if there is a rule of thumb you follow, when deciding whether or not a given property in ObjectiveC should be a retain or copy?

How do you decide which it should be?

Upvotes: 4

Views: 171

Answers (2)

jtbandes
jtbandes

Reputation: 118651

Typically you use copy for safety with classes which have mutable variants, like NSString, NSArray, the other collection classes, etc. To see why, consider what happens here...

Once upon a time,

@interface MyClass : NSObject
@property (retain) NSString *happyString;
- (void)rejoice;
@end

Then one day,

- (void)bigBadMethod {
    MyClass *myObject = [[[MyClass alloc] init] autorelease];
    NSMutableString *theString = [NSMutableString stringWithString:@"I'm happy!"];
    myObject.happyString = theString; // this is allowed because NSMutableString inherits from NSString
    [myObject rejoice]; // prints "I'm happy!"

when suddenly...

    [theString setString:@"BRAAAAIIINNNSSSSS"];
    [myObject rejoice]; // prints "BRAAAAIIINNNSSSSS"
}

And you wouldn't want that, would you? So use @property (copy) if you don't want to get mutated while you're not looking!

Upvotes: 10

PengOne
PengOne

Reputation: 48398

In a nutshell, assign vs retain vs copy determines how the synthesized accessors interact with the Objective-C memory management scheme:

  • assign is the default and simply performs a variable assignment
  • retain specifies the new value should be sent -retain on assignment and the old value sent release
  • copy specifies the new value should be sent -copy on assignment and the old value sent release.

Remember that retain is done on the created object (it increases the reference count) whereas copy creates a new object. The difference, then, is whether you want to add another retain to the object or create an entirely new object.

Upvotes: 2

Related Questions