Category is one of the most commonly used functions in objective-c. The category can add methods to existing classes without adding a subclass. Furthermore, we can add methods to the class without knowing the implementation within a class.
Note: A category cannot declare a new instance variable for a class, he only contains methods.
This article is to add a variable to the class by category, not much to say, directly on the code bar:
The following code is implemented through the runtime:
Static constchar *durationkey ="duration";
-(int) getdurationtime{
return [Objc_getassociatedobject (self, &durationkey) intvalue];
}
-(void) Setdurationtime: ( int ) duration{
objc_setassociatedobject (self, &durationkey, [NSNumber numberwithint:duration], objc_association_retain_nonatomic);
}
Call mode: [selfgetdurationtime];
The true colors of category
OBJC All classes and objects are C structures, the category of course is the same, the following is the runtime structure of category:
12345678 |
struct_category_t {Const Char*name;//1struct_class_t *cls;//2Const struct_method_list_t *instance_methods;//3Const struct_method_list_t *class_methods;//4Const struct_protocol_list_t *protocols;//5Const struct_prop_list_t *properties;//6}; |
name Note that it is not the name written in the category parenthesis, but the name of the class
cls to extend the class object, this value is not available during compilation, when the app is loaded by the runtime will be based on name corresponds to class object
instance_methods this category all - method
class_methods this category all + method
protocolsThis category implementation of the Protocol, relatively not commonly used in the category to implement the Protocol, but does support the
propertiesThis category has all of the property, which is also the category can be defined in the attributes of the reasons, but this will not@synthesizeInstance variables, which are typically required when adding an instance variable propertyobjc_setAssociatedObjectAndobjc_getAssociatedObjectMethod binds a method binding, but this method produces exactly the same thing as a normal instance variable.
How do I add a variable to a category?