iOS runtime实战应用:Method Swizzling
以下属于我的摘着和学习
iOS内功篇:runtime
runtime是一个c和汇编写的动态库,它就像一个小小的系统,将OC和C紧密关联;这个系统主要做两件事
- 封装C语言的结构体和函数,让开发者在运行时创建、检查或修改类,对象和方法等等。
- 传递消息,找出方法的最终执行代码。
栗子:
[student walkTheDog];
那么runtime会将它转化成C语言的代码
objc_msgSend(student, @selector(walkTheDod));
这个方法就是发送消息的方法,类似这样的方法runtime提供了很多,比如:
// 获取属性列表
objc_property_t * class_copyPropertyList ( Class cls, unsigned int *outCount );
// 获取所有方法的数组
Method * class_copyMethodList ( Class cls, unsigned int *outCount );
// 添加方法
BOOL class_addMethod ( Class cls, SEL name, IMP imp, const char *types );
那么我们可以利用这些方法干点什么?
方法调用流程
1> 遍历对象的属性
比如;看看student的有哪些属性(性别,生日)
2> 动态添加/修改属性,动态添加/修改/替换方法
比如: 修改student的性别,生日日期,walkTheDog(变成study)
3> 动态创建Class/Object/Protocol等等...
4> 方法拦截调用(修改实现/添加实现)
比如:Student1发送一个walkTheDog消息, 而walkTheDog方法没有实现,我们可以通过runtime拦截,给方法动态添加一个实现,甚至可以让其他对象Student2来walkTheDog;
下面以实例对象调用 student walkTheDog
为栗子描述方法调用流程:
1> 编译器会把`student walkTheDog` 转化为objc_msgSend(student,@seletor(walkTheDog))
2> `runtime` 会在student实例对象所对应的Student类的方法缓存列表里查找方法SEL
3> 如果没有找到,则在Student类的方法分发表查找方法的SEL。(类由对象isa指针指向,方法分发表即methodList)
4> 如果没有找到,则在其父类的方法分发表里查找方法的SEL(父类由类的superClass指向 [self和super区别](http://blog.csdn.net/li15809284891/article/details/54836905)),如果一直没找到,会到达NSObject基类,最终没有改方法则编译器报错。
5> 如果使用`student preformSelector:@selector:(walkTheDog)`的方式调用方法,需要到运行时才能确定对象能否接收指定的消息,这个时候会进入消息转发流程
消息转发流程
1> 动态方法解析
接收到位置消息时(假设student的walkTheDog方法尚未实现), runtime 会调用 +resolveInstanceMethod:
(实例方法)或者+resolveClassMethod:
(类方法),在该方法中,我们可以给未知消息新增一个已经实现的方法。
void study(id self, SEL _cmd) {
//let the student study
}
+ (BOOL)resolveInstanceMethod:(SEL)sel {
NSString *selString = NSStingFormSelector(sel);
if ([selString isEqualToString:@"walkTheDog"]){
class_addMethod(self.class, @selector(walkTheDog), (IMP)study, "@:");
}
return [super resolveInstanceMethod:sel];
}
2> 备用接收者
如果以上方法都没有做处理, runtime会调用 - (id)forwardingTargetForSelector:(SEL)aSelector
方法。
如果该方法返回了一个非nil (也不是self)的对象,而且该对象实现了这个方法,那么这个对象就成了消息的接收者,消息就被分发到该对象。
适用情况: 通常在对象内部使用,让内部的另一个对象处理消息,在外面看起来就像是对象处理了消息。
-(id)forwardTargetForSelector:(SEL)aSelector {
NSString *selString = NSStringFromSelector(aSelector);
if ([selString isEquaToString:@"walkTheDog"])
return self.student2;
}
return [super forwardingTargetSelector:aSelector];
}
3> 完整消息转发
在- (void)forwardInvocation:(NSInvocation *)anInvocation
方法中选择转发消息的对象,其中anInvocation对象封装了未知消息的所有细节,并保留调用结果发送到原始调用者。
比如:student将消息完整转发brother来处理
- (void)forwardInvocation:(NSInvocation *)anInvocation {
if ([Person instancesRespondToSelector:anInvocation.selector]) {
[anInvocation invokeWithTarget:self.person];
}
}
4> 如果在以上三个方法都没有处理未知消息,则会引发异常。
iOS runtime实战应用:成员变量和属性
成员变量
1、定义:
Ivar: 实例变量类型,是一个指向objc_ivar结构体的指针
typedef struct objc_ivar *Ivar;
2、操作函数:
// 获取所有成员变量
class_copyIvarList
// 获取成员变量名
ivar_getName
// 获取成员变量类型编码
ivar_getTypeEncoding
// 获取指定名称的成员变量
class_getInstanceVariable
// 获取某个对象成员变量的值
object_getIvar
// 设置某个对象成员变量的值
object_setIvar
3、使用实例:
Model的头文件声明如下:
@interface Model : NSObject {
NSString * _str1;
}
@property NSString * str2;
@property (nonatomic, copy) NSDictionary * dict1;
@end
获取其成员变量:
unsigned int outCount = 0;
// 获取所有成员变量
Ivar * ivars = class_copyIvarList([Model class], &outCount);
for (unsigned int i = 0; i < outCount; i ++) {
Ivar ivar = ivars[i];
const char * name = ivar_getName(ivar);
const char * type = ivar_getTypeEncoding(ivar);
NSLog(@"类型为 %s 的 %s ",type, name);
}
free(ivars);
打印结果:
[897:26127] 类型为 @"NSString" 的 _str1
[897:26127] 类型为 @"NSString" 的 _str2
[897:26127] 类型为 @"NSDictionary" 的 _dict1
属性
1、定义:
objc_property_t:声明的属性的类型,是一个指向objc_property结构体的指针
typedef struct objc_property *objc_property_t;
2、操作函数:
// 获取所有属性
class_copyPropertyList
说明:使用class_copyPropertyList并不会获取无@property声明的成员变量
// 获取属性名
property_getName
// 获取属性特性描述字符串
property_getAttributes
// 获取所有属性特性
property_copyAttributeList
说明:
property_getAttributes函数返回objc_property_attribute_t结构体列表,objc_property_attribute_t结构体包含name和value,常用的属性如下:
属性类型 name值:T value:变化
编码类型 name值:C(copy) &(strong) W(weak) 空(assign) 等 value:无
非/原子性 name值:空(atomic) N(Nonatomic) value:无
变量名称 name值:V value:变化
使用property_getAttributes获得的描述是property_copyAttributeList能获取到的所有的name和value的总体描述,如 T@"NSDictionary",C,N,V_dict1
3、使用实例:
unsigned int outCount = 0;
objc_property_t *porperties = class_copyProperList([Model class], &outCount):
for (unsigned int i = 0, i<outCount; i++) {
objc_property_t property = properties[i];
//属性名
const char *name = property_getName(property);
//属性描述
const char *propertyAttr = proper_getAttributes(property);
NSLog(@"属性描述为 %s 的 %s", propertyAttr, name);
//属性的特性
unsigned int attrCount = 0;
objc_property_attribute_t * attrs = property_copyAttributeList(property, &attrCount);
for (unsigned int j = 0; j < attrCount; j ++) {
objc_property_attribute_t attr = attrs[j];
const char * name = attr.name;
const char * value = attr.value;
NSLog(@"属性的描述:%s 值:%s", name, value);
}
free(attrs);
NSLog(@"\n");
}
free(properties);
}
打印结果:
text[1202:55532] 属性名: str2 属性描述: T@"NSString",&,V_str2
text[1202:55532] 属性名: T 值:@"NSString"
text[1202:55532] 属性名: & 值:
text[1202:55532] 属性名: V 值:_str2
text[1202:55532]
text[1202:55532] 属性名: dict1 属性描述: T@"NSDictionary",C,N,V_dict1
text[1202:55532] 属性名: T 值:@"NSDictionary"
text[1202:55532] 属性名: C 值:
text[1202:55532] 属性名: N 值:
text[1202:55532] 属性名: V 值:_dict1
text[1202:55532]
应用实例
1、简单的JSON转模型
- (instancetype)initWithDict:(NSDictionary *)dict {
if (self = [self init]) {
//(1)获取类的属性及属性对应的类型
NSMutableArray * keys = [NSMutableArray array];
NSMutableArray * attributes = [NSMutableArray array];
/*
* 例子
* name = value3 attribute = T@"NSString",C,N,V_value3
* name = value4 attribute = T^i,N,V_value4
*/
unsigned int outCount;
objc_property_t * properties = class_copyPropertyList([self class], &outCount);
for (int i = 0; i < outCount; i ++) {
objc_property_t property = properties[i];
//通过property_getName函数获得属性的名字
NSString * propertyName = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
[keys addObject:propertyName];
//通过property_getAttributes函数可以获得属性的名字和@encode编码
NSString * propertyAttribute = [NSString stringWithCString:property_getAttributes(property) encoding:NSUTF8StringEncoding];
[attributes addObject:propertyAttribute];
}
//立即释放properties指向的内存
free(properties);
//(2)根据类型给属性赋值
for (NSString * key in keys) {
if ([dict valueForKey:key] == nil) continue;
[self setValue:[dict valueForKey:key] forKey:key];
}
}
return self;
}
2、快速归档
- (id)initWithCoder:(NSCoder *)aDecoder {
if (self = [super init]) {
unsigned int outCount;
Ivar * ivars = class_copyIvarList([self class], &outCount);
for (int i = 0; i < outCount; i ++) {
Ivar ivar = ivars[i];
NSString * key = [NSString stringWithUTF8String:ivar_getName(ivar)];
[self setValue:[aDecoder decodeObjectForKey:key] forKey:key];
}
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder {
unsigned int outCount;
Ivar * ivars = class_copyIvarList([self class], &outCount);
for (int i = 0; i < outCount; i ++) {
Ivar ivar = ivars[i];
NSString * key = [NSString stringWithUTF8String:ivar_getName(ivar)];
[aCoder encodeObject:[self valueForKey:key] forKey:key];
}
}
3、访问私有变量
Ivar ivar = class_getInstanceVariable([Model class], "_str1");
NSString * str1 = object_getIvar(model, ivar);