开发者

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

开发者 https://www.devze.com 2023-03-29 17:38 出处:网络
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开发者_Go百科 or copy?

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开发者_Go百科 or copy?

How do you decide which it should be?


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!


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消