我想在我的简单类中使用 ARC,我在其中存储一些值以传递给另一个类。我想知道我必须在属性中使用什么引用。要在 ARC 中使用它,我有这个:
@interface MyItem : NSObject
@property (retain) NSString *valueID;
@property (retain) NSString *itName;
@property (retain) NSDate *creationDate;
@property (assign) float rating;
这是一个非常简单的类,我想知道如何在ARC中使用它。我必须使用什么引用资料?我必须使用 NSString 等的副本吗?
编辑:
如果我有一个 UIViewController,并且我想像这样为 NSString 和 MyItem 对象使用一个属性:
@interface MyViewController : UIViewController
@property (nonatomic, retain) NSString *myString;
@property (nonatomic, retain) MyItem *newItem;
我必须为 NSString 和 MyItem 对象使用什么引用?
最佳答案
您想使用 strong
而不是 retain
。是的,您仍然应该对 NSString
使用 copy
。 copy
的使用与ARC无关;你想要 copy
因为如果有人将 NSMutableString
分配给你的属性,你不希望字符串在你背后改变。使用 copy
为您提供可变字符串在赋值发生点的不可变快照。
这是在 View Controller 示例中声明属性的推荐方式:
@interface MyViewController : UIViewController
@property (nonatomic, copy) NSString *myString;
@property (nonatomic, strong) MyItem *newItem;
NSString
也可以声明为 strong
,但是 copy
几乎总是更适合字符串(实际上任何不可变类型都有可变变体,例如数组、字典等)。
关于ios - 在简单类 object-c 中使用 ARC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11196975/