Owner attributes
Let's take a look at the mappings between attributes and keywords related to ownership.
Attribute Value |
Keywords |
Ownership |
Strong |
_ Strong |
Yes |
Weak |
_ Weak |
None |
Unsafe_unretained |
_ Unsafe_unretained |
None |
Copy |
_ Strong |
Yes |
Assign |
_ Unsafe_unretained |
None |
Retain |
_ Strong |
Yes |
Strong
The _ strong keyword corresponding to the attribute, that is, the variable declared by this attribute will become the owner of the object.
Weak
This attribute corresponds to the _ weak keyword, which is consistent with the variable defined by _ weak. The variables declared by this attribute do not have the ownership of the object, and when the object is discarded, the object is automatically assigned a value of nil.
In addition, delegate and Outlet should be declared using the weak attribute. At the same time, for example, the previous version of iOS 5 does not have the _ weak keyword, so the weak attribute cannot be used. In this case, we use unsafe_unretained.
Unsafe_unretained
It is equivalent to the variable declared by the _ unsafe_unretaind keyword. As described above, the system before iOS 5 uses this attribute to replace weak.
Copy
The difference with strong is that the declaration variable is the holder of the copy object.
Assign
Scalar Varible is declared with this attribute, such as int and BOOL.
Retain
This attribute is consistent with strong, but it is more readable.
Read/write attributes (readwrite, readonly)
Read/write-related attributes include readwrite and readonly. After using ARC, do you need to pay attention to the use of readonly attributes.
For example, the following Variable declaration.
- @property (nonatomic, readonly) NSString *name;
Generally, variables declared as readonly do not require ownership, but the following error message appears when the ARC is valid:
"ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute |
If ARC is defined to be valid, the owner attribute must be defined. Therefore, if our code is changed to this, it will be OK.
- @property (nonatomic, strong, readonly) NSString *name;
However, Scalar Varible variables all have assign attribute definitions by default, so they do not need to be explicitly declared.