ios - 在简单类 object-c 中使用 ARC

标签 ios nsstring automatic-ref-counting retain

我想在我的简单类中使用 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 使用 copycopy的使用与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/

相关文章:

ios - 如何启用/禁用来自应用程序的推送通知?

ios - 如何计算 NSString 中有多少字符直到分号

iphone - 用于右填充 NSString 的 objective-c 代码?

xcode - 为什么有些属性需要 "strong"而有些则不需要?

ios - Objective C 对特定事件的回调

iphone - iOS 开发 : Push notifications prevent my local notifications from firing

iOS:我可以判断用户是否选择退出 Apple 的 "Share With App Developers"设置吗?

ios - 如何在 Objective-C 中测试字符串是否为空?

ios - 框架 iOS ARC

memory-leaks - 与编译时ARC相比,运行时GC有何优势?