正文
最近在准备明年春招(实验室是NLP方向。。。平时还得水一水竞赛task,哎说多了都是泪)
对于runtime平时用的比较少,只遇到如下几个情况:
1,第三方库的只给了.h文件,要实现方法的拓展(直接观察,获取方法列表,然后进行注入),后来发现没有加密的静态库也可以成功hook?好强大,不敢往下想了,微信自动抢红包的插件?
2,为分类添加属性
3,拦截系统的方法,添加计数等新功能等
但是面试面的真的好好好深啊!正好复习整理下,方便春招和以后查阅。
大神请自动掠过,小白是在为小白服务,程序员时间宝贵,不如吃鸡==
先上两张图帮助理解:
runtime:主要用法(Jspatch请忽略,各位尽管Patch。。能通过算我的。。哈哈哈,图比较老了)
元类-父类以及实体的关系图:
##runtime是什么
runtime是属于OC的底层,是一套比较底层的纯C语言API, 属于1个C语言库, 包含了很多底层的C语言API,可以进行一些非常底层的操作(用OC是无法现实的, 不好实现)。 在我们平时编写的OC代码中, 程序运行过程时, 其实最终都是转成了runtime的C语言代码, runtime算是OC的幕后工作者。
runtime中的C语言指针不用的时候需要free()掉,ARC对C语言指针没有办法,只能通过free()方法。
##头文件:
<objc/runtime.h>
<objc/message.h>
必备常识:
//类在runtime中的表示
struct objc_class {
Class isa;//指针,顾名思义,表示是一个什么,
//实例的isa指向类对象,类对象的isa指向元类
Class super_class; //指向父类
const char *name; //类名
long version;
long info;
long instance_size
struct objc_ivar_list *ivars //成员变量列表
struct objc_method_list **methodLists; //方法列表
struct objc_cache *cache;//缓存,一种优化,调用过的方法存入缓存列表,下次调用先找缓存
struct objc_protocol_list *protocols //协议列表
} OBJC2_UNAVAILABLE;
/* Use `Class` instead of `struct objc_class *` */
[target do Something];
会被转化成
objc_msgSend(target, @selector(do Something));
Runtime的主要用法:
在OOP术语中,消息传递是指一种在对象之间发送和接收消息的通信模式。
在Objective-C中,消息传递用于在调用类和类实例的方法,即接收者接收需要执行的消息。
1)消息机制,需要#import <objc/message.h>
执行实质:
如果调用的是类方法:
就会到类对象的isa指针指向的对象(也就是元类对象)中操作。
如果是实例方法:
1,先在相应操作的对象中的缓存方法列表中找调用的方法,如果找到,转向相应实现并执行。
2,如果没找到,在相应操作的对象中的方法列表中找调用的方法,如果找到,转向相应实现执行
3,如果没找到,去父类指针所指向的对象中执行1,2.以此类推,如果一直到根类还没找到,转向拦截调用。如果没有重写拦截调用的方法,抛出异常程序报错。
使用案例:
// 通过类名获取类
//注意Class实际上也是对象,所以同样能够接受消息,向Class发送alloc消息
//报错的话,需要修改Build Setting--> Apple LLVM 6.0 - Preprocessing--> Enable Strict Checking of objc_msgSend Calls 改为 NO
Student *student = [[Student alloc]init];
objc_msgSend(student,@selector(eat));
objc_msgSend(student, @selector(say:),@"这是一句要说的话!" );
2)获取对象的所有属性,方法,成员变量,和遵循的协议(方法比较鸡肋)和添加属性、方法(第4点)等
ivar表示成员变量
class_addIvar
class_addMethod
class_addProperty
class_addProtocol
class_replaceProperty
unsigned int count;
//获取student类的属性列表
objc_property_t *propertyList = class_copyPropertyList([student class], &count);
for (unsigned int i=0; i<count; i++) {
const char *propertyName = property_getName(propertyList[i]);
NSLog(@"property---->%@" , [NSString stringWithUTF8String:propertyName]);
}
free(propertyList);
//获取本类的方法列表
Method *methodList = class_copyMethodList([self class], &count);
for (unsigned int i= 0; i<count; i++) {
Method method = methodList[i];
NSLog(@"method---->%@" , NSStringFromSelector(method_getName(method)));
}
free(methodList);
//获取成员变量列表
Ivar *ivarList = class_copyIvarList([student class], &count);
for (unsigned int i= 0; i<count; i++) {
Ivar myIvar = ivarList[i];
const char *ivarName = ivar_getName(myIvar);
NSLog(@"Ivar---->%@" , [NSString stringWithUTF8String:ivarName]);
}
free(ivarList);
3)方法交换 Method Swizzling(适用场景:
已知类MyClass具有私有方法methodA;要求如何在不改变MyClass源码的基础上扩展methodA方法,使其在执行methodA方法的时候具有新增功能methodB或者 拦截方法调用(Swizzle 黑魔法),也可以说成进行替换)
比如:跟踪程序每个ViewController展示给用户的次数,可以通过Method Swizzling替换ViewDidAppear初始方法。
创建一个UIViewController的分类,重写自定义的ViewDidAppear方法,并在其+load方法中实现ViewDidAppear方法的交换。
实现:借助Runtime的Method Swizzling(方法替换)以及Associated Object(关联对象)
Objective-C 提供了一下API用于动态替换类方法或者实例方法的实现:
class_replaceMethod 替换类方法的定义
method_exchangeImplementations 交换两个方法的实现(具体使用案例如下)
method_setImplementation 设置一个方法的实现
注:class_replaceMethod 试图替换一个不存在的方法时候,会调用class_addMethod为该类增加一个新方法
替换Student类的方法eat和say为:
在Student+MyCategory分类中:
//替换方法, 必须在initialize方法中使用
+(void)initialize{
Method eatMethod = class_getInstanceMethod([self class], @selector(eat));
Method newEatMethod =class_getInstanceMethod([self class],@selector(newEat));
//SEL是方法的索引,IMP是真正的函数地址,因此替换函数,只要将SEL索引互换即可达到效果
method_exchangeImplementations(eatMethod, newEatMethod);
Method sayMethod = class_getInstanceMethod([self class], @selector(say:));
Method newSayMethod =class_getInstanceMethod([self class],@selector(newSay));
method_exchangeImplementations(sayMethod, newSayMethod);
}
-(void)newEat{
NSLog(@"NewEat" );
}
-(void)newSay{
NSLog(@"NewSay" );
}
4)动态添加方法和属性(这个就是Category添加属性的实现本质了):
其中class_addMethod的四个参数分别是:
Class cls 给哪个类添加方法,本例中是self
SEL name 添加的方法,本例中是重写的拦截调用传进来的selector。
IMP imp 方法的实现,C方法的方法实现可以直接获得。如果是OC方法,可以用+ (IMP)instanceMethodForSelector:(SEL)aSelector;获得方法的实现。
"v@:*"方法的签名,代表有一个参数的方法。
//c语言方法
void runAddMethod(id self, SEL _cmd, NSString *string){
NSLog(@"add C IMP %@" , string);
}
//OC方法
-(void)runAddMethod2{
NSLog(@"add OC IMP" );
}
-(void)runTimeAddMethod{
class_addMethod([self class], @selector(runAddMethod:), (IMP)runAddMethod, nil);
IMP imp = [self methodForSelector:@selector(runAddMethod2)];
class_addMethod([self class], @selector(runAddMethod2), imp, nil);
objc_msgSend(self, @selector(runAddMethod:),@"this is a func add at runtime" );
objc_msgSend(self, @selector(runAddMethod2));
}
添加属性:(严格来说为分类添加属性必须要写setter和getter方法,不写的话程序内部只能通过runtime进行读取了)
static char targetKey;
static char actionNameKey;
static char parmatersKey;
-(void)addTarget:(id)target action:(SEL)action paramters:(id)paramters{
//添加属性
self.target = target;
self.actionName = NSStringFromSelector(action);
self.parameter = paramters;
}
-(void)set