Category is used very frequently in iOS development. Especially in the expansion of the system class, we can not inherit the system class, directly to the system class to add methods, the maximum extent of the objective-c dynamic language characteristics.
#import @interface NSObject (Category)-(void) MyMethod; @end
This is the simplest category to use for the NSObject class and adds a method to NSObject.
Points to note in using Category:
(1) The method of category does not have to be implemented in @implementation, but it can be implemented in other locations, but when the method of category is called, the implementation of the method is not found according to the inheritance tree, and the program crashes.
(2) Category theory cannot add variables, but @dynamic can be used to compensate for this deficiency.
#importstatic const void * Externvariablekey =&externvariablekey; @implementation nsobject (Category) @dynamic variable;-(ID) variable{ return Objc_getassociatedobject (self, externvariablekey);} -(void) SetVariable: (ID) variable{
-----------------------------------------------------------
Extension is very much like an unnamed category, that is, an anonymous category
@interface Myclass:nsobject @property (retain, readonly) float value; @end//In general, the extension is placed above the @implementation in the. m file. @interface MyClass () @property (retain, readwrite) float value; @end
Points to note when using extension:
(1) The method in extension must be implemented in the @implementation, otherwise the compilation will error.
It's a little different.
Photo Excerpt: http://blog.sina.com.cn/s/blog_a2c098b50101gsn0.html
iOS category and extensions (Extension, anonymous category)