天天看点

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