Runtime 04 - 應(yīng)用(動(dòng)態(tài)創(chuàng)建類、交換方法)
動(dòng)態(tài)創(chuàng)建類
需要?jiǎng)?chuàng)建的類結(jié)構(gòu)如下
// 人的抽象模型
@interface Person : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) int age;
- (void)sayHello;
- (void)run;
@end
@implementation Person
- (void)sayHello {
NSLog(@"Hi啊央,我是%@眶诈,我今年%d了!", self.name, self.age);
}
- (void)run {
NSLog(@"我跑啊跑啊跑啊跑瓜饥。逝撬。。");
}
@end
// 歌唱家
@protocol Singer
- (void)sing;
@end
// 歌唱明星
@interface Star : Person <Singer>
{
@public
NSString *_company;
}
@end
@implementation Star
- (void)sing {
NSLog(@"la la la so mi ~");
}
@end
動(dòng)態(tài)創(chuàng)建類的示例
先定義一些全局函數(shù)乓土,后面用作 Person 類的屬性方法:
// 從一個(gè) Class 對(duì)象中獲取實(shí)例變量
#define GetIvar(class, name) class_getInstanceVariable(class, name)
// Person 類 name 屬性的 getter
NSString* name(id self, SEL _cmd) {
return object_getIvar(self, GetIvar([self class], "_name"));
}
// Person 類 name 屬性的 setter
void setName(id self, SEL _cmd, NSString *name) {
return object_setIvar(self, GetIvar([self class], "_name"), name);
}
// Person 類 age 屬性的 getter
int age(id self, SEL _cmd) {
return [object_getIvar(self, GetIvar([self class], "_age")) intValue];
}
// Person 類 age 屬性的 setter
void setAge(id self, SEL _cmd, int age) {
return object_setIvar(self, GetIvar([self class], "_age"), @(age));
}
用 Runtime 動(dòng)態(tài)創(chuàng)建一個(gè) Person 類
void allocatePersonClass() {
// 創(chuàng)建 Person 類
Class class = objc_allocateClassPair([NSObject class], "Person", 0);
// 為 name 屬性添加成員變量
class_addIvar(class, "_name", sizeof(NSString*), 1, @encode(NSString));
// 為 age 屬性添加成員變量
class_addIvar(class, "_age", sizeof(int), 2, @encode(int));
// 為 name 屬性添加 getter宪潮、setter
class_addMethod(class, sel_registerName("name"), (IMP)name, "@16@0:8");
class_addMethod(class, sel_registerName("setName:"), (IMP)setName, "v24@0:8@16");
// 為 age 屬性添加 getter、setter
class_addMethod(class, sel_registerName("age"), (IMP)age, "i16@0:8");
class_addMethod(class, sel_registerName("setAge:"), (IMP)setAge, "v20@0:8i16");
// 為 Person 類添加 name 屬性
objc_property_attribute_t nameAttrs[] = {
{"T", "@\"NSString\""}, // 類型:NSString
{"N", ""}, // 原子性:nonatomic
{"C", ""}, // 內(nèi)存管理:copy
{"V", "_name"} // 變量名:_name
};
class_addProperty(class, "name", nameAttrs, 4);
// 為 Person 類添加 age 屬性
const objc_property_attribute_t ageAttrs[] = {
{"T", "i"}, // 類型:int
{"N", ""}, // 原子性:nonatomic
{"V", "_age"} // 變量名:_age
}; // 內(nèi)存管理:默認(rèn) assign
class_addProperty(class, "age", ageAttrs, 3);
// 為 Person 類添加一個(gè) sayHello 方法
class_addMethod(class, sel_registerName("sayHello"), (IMP)sayHello, "v16@0:8");
// 通過(guò) Block 的方式為 Person 類添加一個(gè) run 方法
class_addMethod(class, sel_registerName("run"), imp_implementationWithBlock(^(id self, SEL _cmd) {
NSLog(@"我跑啊跑啊跑啊跑帐我。。愧膀。");
}), "v16@0:8");
// 注冊(cè) Person 類
objc_registerClassPair(class);
}
用 Runtime 動(dòng)態(tài)創(chuàng)建一個(gè) Singer 協(xié)議
void allocateSingerProtocol() {
// 創(chuàng)建 Singer
Protocol *protocol = objc_allocateProtocol("Singer");
// 為 Singer 協(xié)議添加一個(gè) sing 實(shí)例方法
protocol_addMethodDescription(protocol, sel_registerName("sing"), "v16@0:8", YES, YES);
// 注冊(cè) Singer 協(xié)議
objc_registerProtocol(protocol);
}
用 Runtime 動(dòng)態(tài)創(chuàng)建一個(gè) Star 類
void allocateStarClass() {
// 創(chuàng)建 Star 類拦键,繼承自 Person 類
Class class = objc_allocateClassPair(objc_getClass("Person"), "Star", 0);
// 為 Star 類添加 Singer 協(xié)議
class_addProtocol(class, objc_getProtocol("Singer"));
// 為 Star 類添加一個(gè) _company 成員變量
class_addIvar(class, "_company", sizeof(NSString*), 3, @encode(NSString));
// 為 Start 類實(shí)現(xiàn) Singer 協(xié)議中的 sing 方法
class_addMethod(class, sel_registerName("sing"), imp_implementationWithBlock(^(id self, SEL _cmd) {
NSLog(@"la la la so mi ~");
}), "v16@0:8");
// 注冊(cè) Star 類
objc_registerClassPair(class);
}
用 Runtime API 查看 Person 類的結(jié)構(gòu)
-
查看成員變量:
void lookIvars(Class class) { unsigned count; Ivar *ivars = class_copyIvarList(class, &count); // 成員變量列表 for (int i = 0; i < count; i++) { Ivar ivar = ivars[i]; // 成員變量 const char *name = ivar_getName(ivar); // 變量名 const char *typeEncoding = ivar_getTypeEncoding(ivar); // 類型編碼 ptrdiff_t offset = ivar_getOffset(ivar); // 偏移量 printf("%s %s %zd\n", name, typeEncoding, offset); } free(ivars); }
-
查看屬性:
void lookProperties(Class class) { unsigned int count; objc_property_t *properties = class_copyPropertyList(class, &count); // 屬性列表 for (int i = 0; i < count; i++) { objc_property_t property = properties[i]; // 屬性 const char *name = property_getName(property); // 屬性名 const char *attrs_desc = property_getAttributes(property); // 屬性描述 printf("%s %s\n", name, attrs_desc); unsigned attrsCount; objc_property_attribute_t *attrs = property_copyAttributeList(property, &attrsCount); // 描述屬性的屬性列表 for (int j = 0; j < attrsCount; j++) { objc_property_attribute_t attr = attrs[j]; // 描述屬性的屬性 printf("%s %s\n", attr.name, attr.value); // name:名稱,value:值 } printf("\n"); } free(properties); }
-
查看方法:
void lookMethods(Class class) { unsigned int count; Method *methods = class_copyMethodList(class, &count); // 方法列表 for (int i = 0; i < count; i++) { Method method = methods[i]; // 方法 const char *name = sel_getName(method_getName(method)); // 方法名 const char *typeEncoding = method_getTypeEncoding(method); // 類型編碼 printf("%s %s\n", name, typeEncoding); } free(methods); }
allocatePersonClass(); Class class = objc_getClass("Person"); printf("\n---- 變量 ----\n"); lookIvars(class); printf("\n---- 屬性 ----\n"); lookProperties(class); printf("\n---- 方法 ----\n"); lookMethods(class);
通過(guò)打印結(jié)果可以看到動(dòng)態(tài)創(chuàng)建的類結(jié)構(gòu)正常檩淋。
使用 Star 創(chuàng)建對(duì)象芬为,并訪問(wèn)屬性、成員變量蟀悦、方法
allocatePersonClass(); allocateSingerProtocol(); allocateStarClass(); Class class = objc_getClass("Star"); id star = [[class alloc] init]; [star setValue:@"鍋蓋" forKey:@"name"]; NSString *name = [star valueForKey:@"name"]; [star setValue:@22 forKey:@"age"]; int age = [[star valueForKey:@"age"] intValue]; object_setIvar(star, GetIvar(class, "_company"), @22); NSString *company = object_getIvar(star, GetIvar(class, "_company")); NSLog(@"Star:%@, %d, %@", name, age, company); [star performSelector:NSSelectorFromString(@"sayHello")]; [star performSelector:NSSelectorFromString(@"run")]; [star performSelector:NSSelectorFromString(@"sing")];
通過(guò)打印結(jié)果可以看到 Star 可以正常使用媚朦。
交換方法實(shí)現(xiàn)
需求是為所有 ViewController 的生命周期方法進(jìn)行埋點(diǎn),可以通過(guò) Runtime 已少量的代碼實(shí)現(xiàn)日戈,并且不需要在每個(gè) ViewController 的生命周期方法中增加代碼询张。
@interface UIViewController (Hook)
@end
@implementation UIViewController (Hook)
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^ {
// hook:鉤子函數(shù)
Method method1 = class_getInstanceMethod(self, @selector(viewDidLoad));
Method method2 = class_getInstanceMethod(self, @selector(hook_viewDidLoad));
method_exchangeImplementations(method1, method2);
});
}
- (void)hook_viewDidLoad {
// do someting...
[self hook_viewDidLoad];
}
@end
objc_property_attribute_t
用來(lái)描述一個(gè)屬性的類型、讀寫(xiě)性浙炼、內(nèi)存管理份氧、原子性、變量名弯屈。
typedef struct {
const char * _Nonnull name;
const char * _Nonnull value;
} objc_property_attribute_t;
-
類型:
- name:T
- value:
- 基本數(shù)據(jù)類型:i - int蜗帜,f - float,d - double资厉,q - NSInteger厅缺,Q - NSUInteger
- id:@
- 對(duì)象類型:@"ClassName",例如 @"NSString"
- Block:@?
-
讀寫(xiě)性:
- name:readwrite - 無(wú)(默認(rèn))宴偿,readonly - R
- value:""
-
內(nèi)存管理:
- name:assign - 無(wú)(基本數(shù)據(jù)類型時(shí)為默認(rèn))湘捎,strong - &(對(duì)象類型時(shí)為默認(rèn)),weak - W窄刘,copy - C
- value:""
-
原子性:
- name:atomic - 無(wú)(默認(rèn))消痛,nonatomic - N
- value:""
-
變量名:
- name:V
- value:變量名
使用 property_getAttributes() 函數(shù)獲取的是一個(gè)屬性所有 objc_property_attribute_t 的字符串拼接:
- 類型、讀寫(xiě)性都哭、內(nèi)存管理秩伞、原子性逞带、變量名。
- (attr1.name + attr1.value), (attr2.name + attr2.value)