复制vs强属性

我在iOS中比较新鲜,我想知道我们应该在属性中使用copy ,例如

 @property (nonatomic, retain) NSString* name; 

VS

 @property (nonatomic, copy) NSString* name;` 

retaincopy之间有什么区别,我何时应该使用一个而不是另一个?

 @property (nonatomic, copy) NSString* name; 

更好,因为NSString是不可变的,它的子类NSMutableString是可变的。

只要您使用NSString ,您就不会发现任何差异。 但是当你开始使用NSMutableString ,事情可能会变得有点冒险。

 NSMutableString *department = [[NSMutableString alloc] initWithString:@"Maths"]; Person *p1 = [Person new]; p1.department = department; //Here If I play with department then it's not going to affect p1 as the property was copy //eg [department appendString:@"You're in English dept."]; 

如果只是保留它会改变p1的部门。 因此,在这种情况下优先考虑复制。

如果NSStringmutable那么它就会被copied 。 如果不是,则retained它如果您将使用copy ,则将创建该字符串的新副本,因此也会创建不同的内存地址。 然而,如果您将使用retain那么它将位于相同的内存地址中,只有保留计数器才会更改。