What is the rule for using @property (copy) vs. @property (save)?

I wonder if there is a correct rule that you follow when deciding whether a given property in ObjectiveC should be retain or copy ?

How do you decide what it should be?

+4
source share
2 answers

Typically, you use copy for security with classes that have mutable options like NSString , NSArray , other collection classes, etc. To understand why, think about what is happening 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 don’t want this, do you? So use @property (copy) if you don't want to mutate until you look!

+10
source

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

  • assign by default and simply assigns a variable
  • retain indicates that the new value should be sent - receive when assigned and the old value sent by the release
  • copy indicates that the new value should be sent -copy when assigned, and the old value sent.

Remember that retain is executed for the created object (it increases the number of links), while copy creates a new object. The difference is whether you want to add another save to the object or create a completely new object.

+2
source

All Articles