Clarification on assign, retain, copy, strong?

2020-05-13 04:04发布

问题:

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

Thanks....

回答1:

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

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

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.



回答2:

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

copy mutable objects, or objects with mutable subclasses such as NSString: this stops them being modified by another owner. although i don't think its recommended by apple to use mutable objects as properties

other objects are generally retained, with an exception being delegates, which are assigned to prevent ownership loops

primitives like int and BOOL are assigned, this is the default option for @property so doesnt need to be specified, although it doesnt hurt to add it in if you feel it helps the readability