天天看點

NSString property中應該使用copy

For attributes whose type is an immutable value class that conforms to the NSCopying protocol, you almost always should specify copy in your @property declaration. Specifying retain is something you almost never want in such a situation.

Here's why you want to do that:

NSMutableString   * someName  =   [ NSMutableString  stringWithString :@ "Chris" ];

Person   * p  =   [[[ Person  alloc ]  init ]  autorelease ];

p . name  =  someName ;

[ someName setString :@ "Debajit" ];

The current value of the Person.name property will be different depending on whether the property is declared retain or copy — it will be @"Debajit" if the property is marked retain, [email protected]"Chris" if the property is marked copy.

Since in almost all cases you want to prevent mutating an object's attributes behind its back, you should mark the properties representing them copy. (And if you write the setter yourself instead of [email protected] you should remember to actually use copy instead of retain in it.)

由此,我們也可以看出copy和retain的差別了。

如果NSString存的是NSMutableString時  copy是深copy,傳回的是另外一個對象 retainCount=1

NSString 是不可變的NSString時 copy是淺copy,retain +1,但是copy傳回的NSString不可修改,retain可修改

FROM http://www.cnblogs.com/scorpiozj/archive/2011/01/25/1944496.html