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

way*_*neh 8 iphone xcode objective-c

我仍然是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
Run Code Online (Sandbox Code Playgroud)

谢谢....

小智 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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

在您的情况下,更改主要是myColor.您不会使用,retain因为您不直接管理引用计数.该strong关键字是主张财产,类似的"所有权"的一种方式retain.还提供了一个附加关键字weak,通常用于代替对象类型的赋值.Apple的一个常见的weak财产示例是代表.除了内存管理指南之外,我建议您阅读一段时间或更早过渡到ARC发行说明,因为在SO帖子中可以轻松覆盖更多的细微差别.