复制与强大的属性

Kri*_*nki 10 iphone cocoa objective-c ios

我在iOS中比较新鲜,我想知道什么时候我们应该copy在一个属性中使用,例如

@property (nonatomic, retain) NSString* name;
Run Code Online (Sandbox Code Playgroud)

VS

@property (nonatomic, copy) NSString* name;`
Run Code Online (Sandbox Code Playgroud)

retain和之间有什么区别,什么copy时候应该使用一个而不是另一个?

Ind*_*ore 11

@property (nonatomic, copy) NSString* name;
Run Code Online (Sandbox Code Playgroud)

更好,因为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."];
Run Code Online (Sandbox Code Playgroud)

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


Mun*_*hil 5

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


归档时间:

查看次数:

4319 次

最近记录:

9 年,7 月 前