我是iOS方面的新手,我想知道在一个属性中什么时候应该使用copy
关键字,例如:
@property (nonatomic, retain) NSString* name;
vs
@property (nonatomic, copy) NSString* name;`
retain
和copy
有什么区别,我在什么情况下应该使用其中的一个而不是另一个?
我是iOS方面的新手,我想知道在一个属性中什么时候应该使用copy
关键字,例如:
@property (nonatomic, retain) NSString* name;
vs
@property (nonatomic, copy) NSString* name;`
retain
和copy
有什么区别,我在什么情况下应该使用其中的一个而不是另一个?
@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
//e.g.
[department appendString:@"You're in English dept."];
如果只是保留,它会改变 p1
的部门。所以在这种情况下最好复制。
如果 NSString
是可变的,则会进行 复制
。如果不是,则会进行 保留
。
如果使用 copy
,则会创建字符串的新副本,因此内存地址也不同。而如果使用 retain
,则它将在相同的内存地址中,只有保留计数器会更改。
retain
在 ARC 中已经不再使用。你应该用strong
来替换它。 - Christian Schnorr