【问题标题】:Clarification on assign, retain, copy, strong?澄清分配,保留,复制,强?
【发布时间】:2012-01-27 15:25:08
【问题描述】:

我还是 Objective-C 的新手,在尝试找出设置属性时使用分配、保留、复制、强等的适当方法时遇到了一些困难。

例如,我声明了以下类型 - 我应该如何设置属性?

@property (nonatomic, ??) NSMutableArray *myArray
@property (nonatomic, ??) NSString *myString
@property (nonatomic, ??) UIColor *myColor
@property (nonatomic, ??) int *myIn
@property (nonatomic, ??) BOOL *myBOOL

谢谢....

【问题讨论】:

    标签: iphone objective-c xcode


    【解决方案1】:

    重申一下,它确实取决于上下文。在非 ARC 情况下:

    @property (nonatomic, copy) NSMutableArray *myArray
    @property (nonatomic, copy) NSString *myString
    @property (nonatomic, retain) UIColor *myColor
    //Note the change to an int rather than a pointer to an int
    @property (nonatomic, assign) int myInt
    //Note the change to an int rather than a pointer to an int
    @property (nonatomic, assign) BOOL myBOOL
    

    myArray 上的副本是为了防止您设置的对象的另一个“所有者”修改。在 ARC 项目中,情况会发生一些变化:

    @property (nonatomic, copy) NSMutableArray *myArray
    @property (nonatomic, copy) NSString *myString
    @property (nonatomic, strong) UIColor *myColor
    //Note the change to an int rather than a pointer to an int
    @property (nonatomic, assign) int myInt
    //Note the change to an int rather than a pointer to an int
    @property (nonatomic, assign) BOOL myBOOL
    

    在您的情况下,更改主要针对 myColor。您不会使用retain,因为您没有直接管理引用计数。 strong 关键字是断言属性“所有权”的一种方式,类似于retain。还提供了一个额外的关键字weak,它通常用于代替对象类型的assign。 Apple 的weak 属性的常见示例是代表。除了Memory Management Guide 之外,我建议一两次通过Transitioning to ARC Release Notes,因为其中的细微差别比SO 帖子中容易涵盖的要多。

    【讨论】:

    【解决方案2】:
    @property (nonatomic, copy) NSMutableArray *myArray
    @property (nonatomic, copy) NSString *myString
    @property (nonatomic, retain) UIColor *myColor
    @property (nonatomic) int myIn
    @property (nonatomic) BOOL myBOOL
    

    复制可变对象,或具有可变子类的对象,例如NSString:这会阻止它们被另一个所有者修改。虽然我不认为苹果推荐它使用可变对象作为属性

    通常会保留其他对象,但委托是例外,它们被分配以防止所有权循环

    分配了intBOOL 之类的原语,这是@property 的默认选项,因此不需要指定,尽管如果您觉得它有助于提高可读性,添加它也无妨

    【讨论】:

    • 为什么 Apple 不推荐使用可变对象作为属性? (我应该澄清一下,这些都在单例中)
    • 我认为这是一件安全的事情,比如你将 NSMutableString 传递给一个保留它的对象。该对象现在可以修改您的数据(如果它们是您的类,这可能是您想要的,但如果不是,则坚持不可变类型更安全)。与其说是硬性规定,不如说是建议
    • 我明白了。我在我的课程中使用这些作为单身人士,他们确实需要改变。我也在尝试设置一个不可变数组,但是有问题。谢谢你的帮助。 stackoverflow.com/questions/9026679/…
    • @wattson 将可变对象声明为复制属性的全部意义在于避免其他所有者修改它们。只要复制它们(这是 Apple 的建议),就没有理由不将它们用作属性。
    • @UIAdam 你是对的,复制它们是安全的。但我在想,如果你有一个可变属性,那么一个引用你的类的对象可以改变数据,这可能是它的设计方式,但对我来说它似乎不是很好的封装
    猜你喜欢
    • 2012-04-04
    • 1970-01-01
    • 2011-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-30
    • 2014-02-21
    • 2011-05-04
    相关资源
    最近更新 更多