26th: do not declare attributes in the category. Do not declare attributes in the 26th categories.
AttributeIs the way to encapsulate data (see 6th ).
Attributes only define instance variables and relatedAccess MethodThe"Syntactic sugar", So we should also follow the sameInstance variablesSame rules.
Classification mechanism, Should be understood as a means, the goal is to expand the class function, not encapsulate data.
Although technically, attributes can be declared in categories, this approach should be avoided as much as possible.
The reason is: Apart fromClass-continuation category"(See article 27th), other classes cannot add instance variables to the class, so they cannot synthesize the instance variables required to implement the attributes.
Therefore, developers need to implement an access method for this attribute in the category.
1) You can declare the method@ DynamicThat is to say, the compiler is invisible when these methods are provided at runtime. If you decide to use the message forwarding mechanism (see article 12th) inRuntimeThis method may be used to intercept method calls and provide its implementation.
2)Associated object(See article 10th) This solves the problem that instance variables cannot be merged in a category.
Disadvantage: similar code needs to be written many times, andMemory ManagementErrors may occur.
Example:
# Import <Objc/runtime. h>
Static const Char* KFriendsPropertyKey = "kFriendsPropertyKey ";
@ Implementation Person (Friendship)
-(NSArray *) friends {
ReturnObjc_getAssociatedObject(Self, kFriendsPropertyKey );
}
-(Void) setFriends :( NSArray *) friends {
Objc_setAssociaedObject(Self, kFriendsPropertyKey, friends, OBJC_ASSOCIATION_NONATOMIC );
}
@ End
3,Read-only attributeIt can be used in classification. The attributes do not need to be implemented by instance variables.
Because the read-only attribute has only one. mGetterMethod,
That is, all the methods required for this attribute are implemented, so the compiler will not automatically synthesize instance variables for the attribute. The above conditions are met, and the compiler will not issue a warning message.
Summary:
Even if these three methods can be implemented, it is not recommended.
Instead, all the attributes used to encapsulate data should be defined inMain Interface.
In theClass-continuation categoryIn other categories, you can define an access method, but do not define attributes.