关于分配,保留,复制,强大的澄清?

时间:2012-01-27 15:25:08

标签: iphone objective-c xcode

我仍然是Objective-C的新手,并且在设置属性时尝试找出使用assign,retain,copy,strong等的适当方法时遇到了一些困难。

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

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

...谢谢

2 个答案:

答案 0 :(得分:20)

重申一下,它确实取决于背景。在非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,通常用于代替对象类型的赋值。 Apple的weak属性的常见示例是代表。我建议除Transitioning to ARC Release Notes之外的Memory Management Guide一两次,因为有更多的细微差别,而不是SO帖子中容易涵盖的。

答案 1 :(得分:0)

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

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

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

分配了像<{1}}和int这样的原语,这是@property的默认选项,所以不需要指定,但如果你认为它有助于提高可读性,那么添加它不会有什么害处< / p>