Differences between categories, extensions, and subcategories of categories, extensions, and subclasses of iOS
|
class |
extension |
subclass |
| Function |
Add a method to the class, do not know the source code of the class, add the variable (through the runtime, the following note for specific reference) |
Add private variables and private methods to the class, write in the source file of the class, and know the source code of the class |
The ability to add a method to a class and add a variable |
| Characteristics |
The added method is called part of the class and can be inherited by the quilt class |
The variables and methods that are added are accessible only within this class, and are not normally accessible outside of normal circumstances (can be accessed through runtime, see annotations) and cannot be inherited by a quilt class |
Newly added variables and methods can only be child classes, and the parent class does not have |
| Use |
Invoke methods using the original class's object (call-method) or class (call + method) |
Use inside the class (source file) |
Only subclasses can use |
Note 1: Adding a variable to a category the first step is to add a variable
@interface UIView (Desc)@property (nonatomic, copy) NSString *name;@end
Second step: Add the corresponding setter and getter method in the source file (cannot be written according to normal setter and getter method, need to use runtime)
1)先在外边添加一个静态变量 static char keyString = ‘a’; 2)在源文件中添加setter和getter - (NSString*)name { Objc_getAssociatedObject(self,&keyString); } - (void)setName:(NSString*)name{ Objc_setAssociatedObject(self,&keyString,name, OBJC_ASSOCIATION_COPY); }
2, in the extension for the class to add a private variable, how to get
Ivar* members = class_copyIvarList([MYClass class], &varCount); for (int i= 0; i<varCount; i++) { Ivar member = members[i]; const char* name = ivar_getName(member); const char* type = ivar_getTypeEncoding(member); NSLog(@"name:%s, type:%s",name,type); }
Wen/daniel_guo (author of Jane's book)
Original link: http://www.jianshu.com/p/2613b8412635
Copyright belongs to the author, please contact the author to obtain authorization, and Mark "book author".
Differences between iOS classification, extension, and subclasses