Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 237
James Raitsev Avatar asked Dec 16 '22 10:12

James Raitsev


1 Answers

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!

like image 54
jtbandes Avatar answered Dec 19 '22 00:12

jtbandes