【问题标题】:copy vs strong properties [duplicate]复制与强属性[重复]
【发布时间】:2015-09-21 22:03:45
【问题描述】:

我对 iOS 比较熟悉,我想知道什么时候应该在属性中使用 copy,例如

@property (nonatomic, retain) NSString* name;

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

retaincopy 有什么区别,什么时候应该使用其中一个而不是另一个?

【问题讨论】:

  • 一般来说,我对 NSString、数组和其他变量等对象使用保留。但是当我将 UIView 的出口或任何实例作为 UIViewController 时,我会变得坚强。否则实际上我不知道区别。
  • @ArpitParekh 强 === 保留:stackoverflow.com/questions/7796476/…
  • 但是,当我将 UIViewController 作为一个变量,并且我需要将它分配为一个强大的属性时,如果我将它作为一个保留,那么我的应用程序就会崩溃......这个链接支持这个。将其添加为子视图时stackoverflow.com/questions/9144959/…
  • @ArpitParekh retain 自 ARC 起不再使用。您应该将其替换为 strong

标签: ios objective-c iphone cocoa


【解决方案1】:
@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 的部门。 所以在这种情况下最好有副本。

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 你的意思是当在属性中如果 NSString 属性然后我使用保留,当我使用 NSMutableString 时我需要使用 COPY 对吗?
    • NSString 从不可变。因此需要 NSMutableString...
    猜你喜欢
    • 2013-10-15
    • 2011-11-29
    • 2014-08-29
    • 2011-08-19
    • 2012-01-09
    • 2016-01-12
    • 1970-01-01
    • 2017-01-06
    • 2021-08-24
    相关资源
    最近更新 更多