关于分配,保留,复制,澄清的澄清? [英] Clarification on assign, retain, copy, strong?
问题描述
我仍然是Objective-C的新手,并且在设置属性时尝试找出使用assign,retain,copy,strong等的适当方法时遇到了一些困难。
I'm still new to Objective-C and having some difficulties trying to figure out the appropriate way to use assign, retain, copy, strong, etc. when setting a property.
例如,我声明了以下类型 - 我应该如何设置属性?
For example, I have the following types declared - how should I be setting the properties?
@property (nonatomic, ??) NSMutableArray *myArray
@property (nonatomic, ??) NSString *myString
@property (nonatomic, ??) UIColor *myColor
@property (nonatomic, ??) int *myIn
@property (nonatomic, ??) BOOL *myBOOL
谢谢.. ..
推荐答案
重申一下,它确实取决于上下文。在非ARC情况下:
To reiterate, it does depend on context. In an non-ARC situation:
@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项目中,事情发生了一些变化:
The copy on myArray is to prevent modification by another "owner" of the object you set. In an ARC project, things change a bit:
@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。您不会使用保留
,因为您不直接管理引用计数。 strong
关键字是一种断言属性所有权的方式,类似于 retain
。还提供了另一个关键字 weak
,通常用于代替对象类型的赋值。 Apple的一个弱
属性的常见示例是代表。我建议您浏览过渡到ARC发行说明除了内存管理指南,还有一两次,因为还有更多细微差别很容易被SO帖子所覆盖。
The change is primarily to myColor in your situation. You wouldn't use retain
as you aren't managing reference counting directly. The strong
keyword is a way of asserting "ownership" of the property and similar to retain
. An additional keyword is also provided, weak
, that would typically be used in place of assign for object types. Apple's common example of a weak
property is for delegates. I'd recommend going through the Transitioning to ARC Release Notes in addition to the Memory Management Guide a time or two as there is more nuance than can easily be covered in an SO post.
这篇关于关于分配,保留,复制,澄清的澄清?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!