Clarification on assign, retain, copy, strong?

前端 未结 2 1924
心在旅途
心在旅途 2021-01-30 12:07

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.

F

相关标签:
2条回答
  • 2021-01-30 12:36
    @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

    0 讨论(0)
  • 2021-01-30 12:45

    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.

    0 讨论(0)
提交回复
热议问题