Runtime在我心目中一直是神秘的,本文是前两天对Runtime学习的一个总结。
前言
因为OC在编译和链接时推迟了很多操作,放到了运行时。这就是所谓的动态,所以此时不仅仅需要编译器,而且也需要一个运行时系统去执行这些编译后的代码。
其实Runtime看似神秘,其实我们每天都在和他打交道。当我们正常编写OC代码编译的时候,Runtime就会自动的为我们做一些事情, 比如开启ARC后在运行时Runtime会自动的添加objc_retain, objc_release , objc_autorelease等内存管理方法; 当我们使用到isKindOfClass:, respondsToSelector:,conformsToProtocol:, load等一些NSObject协议中或者类中方法时,其实也是和Runtime进行交互了,因为这些方法都是在运行的时候,向Runtime去询问信息的;
Non-fragile ivars
Runtime分两个版本,modern 和 legacy,iOS开发的时候就是modern了。 modern 和 legacy两个版本的主要区别就是,modern支持了Non-fragile ivars特性。 Non-fragile ivars就是当改变类的成员变量结构后,本类的子类的对象不需要重新编译,还可以正常运行,但是在legacy时,就必须重新编译了。
一般当iOS系统更新的时候,可能会在基类中增加一些新的成员变量,此时原本工程中的子类的结构因为在编译的时候已经确定,于是就和新版本的基类结构产生冲突,所以必须要重新编译;而且如果这些子类是一个工程中的某个第三方库,那么我们就只能等作者更新,所以这种痛苦我们iOS开发者是体会不到的😂。
而modern 的Runtime就可以解决这个问题,当iOS系统更新时,在基类中增加一些新的成员变量后,在运行时,Runtime会动态调整子类的结构,从而不会产生重叠,于是不用重新编译就可以运行了。此时OC的库从此具有了二进制兼容性,当iOS版本不断更新,这个iOS库还是可以正常被使用。
消息机制
OC其实是封装了C语言,使其具有面向对象的特性,同时参考了
Smalltalk的消息机制。
objc_msgSend
OC中我们调用方法一般使用中扩号语法,如下:
[longjianjiang eat:@"apple"]当运行时,所有的方法调用都会被Runtime转换为发送消息的方式,也就是通过objc_msgSend函数去实现。所以上述的方法调用就会被转化为下面的函数调用(我们直接这样写会报错,这是编译器自动进行转化的):
objc_msgSend(longjianjiang, @selector(eat), @"apple")消息发送的过程
根据selector寻找对应的IMP
1.首先去methodLists中去寻找;
这里得了解下OC中对象和类的大致结构(以下代码摘自objc4-709):
struct objc_object {
private:
isa_t isa;
};struct objc_class : objc_object {
Class superclass;
const char *name;
uint32_t version;
uint32_t info;
uint32_t instance_size;
struct old_ivar_list *ivars;
struct old_method_list **methodLists;
Cache cache;
struct old_protocol_list *protocols;
// CLS_EXT only
const uint8_t *ivar_layout;
};struct old_method {
SEL method_name;
char *method_types;
IMP method_imp;
};
struct old_method_list {
void *obsolete;
int method_count;
#ifdef __LP64__
int space;
#endif
/* variable length structure */
struct old_method method_list[1];
};看了上述的结构,我们应该可以猜想到寻找的过程应该如下图所示:

我们注意到类的结构体中有个
cache,是之前被调用过的方法。所以在methodLists中寻找之前,Runtime会在cahce中寻找。这样可以加速执行速度。
2.动态增加实现
如果第一步中没有找到selector对应的IMP怎么办呢?
此时Runtime会在类中寻找是否有实现resolveInstanceMethod:方法,该方法可以动态的为类的实例方法增加一个实现,对应的resolveClassMethod:可以动态的为类的类方法增加一个实现。如下代码所示Person类中为eat方法动态增加了实现:
void dynamicMethodIMP(id obj, SEL _cmd) {
NSLog(@"%@",NSStringFromClass([obj class]));
[obj writeSomeThing:@"JJJJJJJJJ"];
NSLog(@"eat delicious food");
}
+ (BOOL)resolveInstanceMethod:(SEL)sel {
if (sel == @selector(eat)) {
IMP eatIMP = imp_implementationWithBlock(^(id obj) {
Person* p = (Person*)obj;
NSLog(@"%@",NSStringFromClass([obj class]));
NSLog(@"eat delicious food");
[p writeSomeThing:@"test"];
});
class_addMethod([self class], sel, (IMP)dynamicMethodIMP , "v@:");
return YES;
}
return [super resolveInstanceMethod:sel];
}上述代码通过
class_addMethod方法给类增加了一个方法,我们可以发现其实OC中的方法和普通的C语言函数没什么不同就是增加了两个参数:self和_cmd ,也就是调用方法者和方法的selector。
3.消息转发
如果经过前面两步,依然没有找到对应的IMP,此时Runtime会再给最后一次机会,如下代码Person类实现了sing消息的转发:
// 2. 检测生成的方法签名的参数和返回值是否和selector的一致
// 然后去forwardInvocation:方法
-(NSMethodSignature*)methodSignatureForSelector:(SEL)selector {
NSMethodSignature *signature = [super methodSignatureForSelector:selector];
if (! signature) {
//生成方法签名
signature = [singer methodSignatureForSelector:selector];
}
return signature;
}
// 3. 根据invocation中包含的信息调用invokeWithTarget:方法
- (void)forwardInvocation:(NSInvocation *)anInvocation {
SEL aSelector = [anInvocation selector];
if (aSelector == @selector(sing)) {
if ([singer respondsToSelector:aSelector])
[anInvocation invokeWithTarget:singer];
else
[super forwardInvocation:anInvocation];
}
}
// 1. 首先判断该方法是否实现,如果实现直接去返回的对象中寻找selector的IMP,
// 否则去methodSignatureForSelector:方法
- (id)forwardingTargetForSelector:(SEL)aSelector {
return singer;
}如果转发失败,则会去调用doesNotRecognizeSelector方法,这时候就会出现一个我们熟悉的错误:
此时的
doesNotRecognizeSelector其实是调用的NSObject的forwardInvocation:中的实现;
-[Person sing]: unrecognized selector sent to instance 0x10046cde0
最后
未完待续。