复制属性 vs 强引用属性

10

我是iOS方面的新手,我想知道在一个属性中什么时候应该使用copy关键字,例如:

@property (nonatomic, retain) NSString* name;

vs

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

retaincopy有什么区别,我在什么情况下应该使用其中的一个而不是另一个?


通常,我会在NSString、数组和其他变量等对象上使用retain。但是当我获取UIView的outlets或任何UIViewController实例时,我会使用strong。否则,我实际上不知道它们之间的区别。 - Arpit B Parekh
4
@ArpitParekh 中的 "strong" 等同于 "retain":https://dev59.com/IWsz5IYBdhLWcg3wlY69 - DanZimm
但是,当我将UIViewController作为变量时,并且需要将其分配为强属性时,如果我将其设置为retain,则我的应用程序会崩溃...此链接支持此操作。在将其添加为子视图时http://stackoverflow.com/questions/9144959/how-to-retain-view-after-addsubview-of-uiviewcontroller-with-arc - Arpit B Parekh
1
@ArpitParekh retain 在 ARC 中已经不再使用。你应该用 strong 来替换它。 - Christian Schnorr
2个回答

12
@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 的部门。所以在这种情况下最好复制。


5

如果 NSString 是可变的,则会进行 复制。如果不是,则会进行 保留。 如果使用 copy,则会创建字符串的新副本,因此内存地址也不同。而如果使用 retain,则它将在相同的内存地址中,只有保留计数器会更改。


你的意思是如果属性中使用了NSString属性,那么我需要使用retain,而当我使用NSMutableString时,我需要使用COPY,对吗? - Krish Solanki
1
NSString从来不可变。因此需要NSMutableString... - DanZimm

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接