iOS开发

runtime详解

2017-12-14  本文已影响21人  Mrfengzi

runtime详解

1,runtime的核心—消息传递

在[object foo]在运行的过程中会给object发送foo消息,但是这个消息可能会被转发到另一个对象,也可能
并不会立即执行foo这个发放的代码。它在运行时给object发送一个叫foo的消息,这个消息也许会由object来处理。也许会转发给另一个对象,或者不接收这个消息有另一个方法来实现这个消息
在编译时,Object-C函数调用的语法会被编译成一个C的函数调用 - objc_mesSend(),- objc_mesSend(object, @selector(), arg)

struct objc_object {  
    Class isa  OBJC_ISA_AVAILABILITY;
};

struct objc_class {  
    Class isa  OBJC_ISA_AVAILABILITY;
#if !__OBJC2__
    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;
#endif
};
struct objc_method_list {  
    struct objc_method_list *obsolete;
    int method_count;

#ifdef __LP64__
    int space;
#endif

    /* variable length structure */
    struct objc_method method_list[1];
};

struct objc_method {  
    SEL method_name;
    char *method_types;    /* a string representing argument/return types */
    IMP method_imp;
};

从API中可以看出oc的对象是一个指向objc_object(对象)结构体的指针。Class是一个指向objc_class(类)结构体的指针。每个结构体中都包含一个isa指针,isa指针指向的类结构。
objc_mesSend(object, @selector(), arg) 消息传递的过程是:先通过object的isa指针找到class,在class的object_cache找到改函数(object_cache是以method_name作为key,method_imp为value存储的能够直接查找),如果object_cache找不到会从class的methodList找改函数(从API中可以看出methodList其实是一个数组,查找效率太低),再找不到会从他的superclass中找,如果再找不到,如果我们不做特殊处理程序就会挂掉

2,消息传递补救:

如果消息未被实现时,runtime调用resolveInstanceMethod实现

+ (BOOL)resolveInstanceMethod:(SEL)aSEL 
{
    //添加某个方法的实现
    if(aSEL == name){
        class_addMethod(Class cls, SEL name, IMP imp,
                    const char *types)
    }
    
    return YES;
}  

resolveInstanceMethod:方法返回YES时系统会从新发送一次消息,在返回YES之前添加没有实现的方法
如果resolveInstanceMethod没有特殊处理系统会调用forwardingTargetForSelector方法把消息转发给另一个对象

- (id)forwardingTargetForSelector:(SEL)aSelector
{
    if(aSelector == SEL){
        return newObject;
    }
    return [super forwardingTargetForSelector:aSelector];
}

当forwardingTargetForSelector返回nil,系统会发送methodSignatureForSelector消息获得函数的返回值类型。如果 -methodSignatureForSelector: 返回 nil ,系统会发出doesNotRecognizeSelector消息,这时就无力会天了。如果返回了一个函数签名,Runtime 就会创建一个 NSInvocation 对象并发送 -forwardInvocation: 消息给目标对象。

- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
{
}

runtime使用的几种场景

1,添加category属性(关联对象)

objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)
objc_getAssociatedObject(id object, const void *key)

程序会在执行某个类的load,initialize方法时候执行分类属性
category不能够直接添加属性是因为oc的对象objc_class结构体大小是固定的,不可能往这个结构体中添加数据,只能修改
category能够直接添加方法是因为oc的对象的objc_object结构体里面的methodList是一个二维数组,所以可以修改*methodLists的值来增加成员方法,虽没办法扩展methodLists指向的内存区域,却可以改变这个内存区域的值

2,动态得到属性和方法

(1)获取property属性:

unsigned int outCount;
objc_property_t *objc_property_t = class_copyPropertyList([self class], &outCount)
for (int i = 0; i < outCount; i ++) {
    objc_property_t property = properties[i];
    NSString * propertyName = [[NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
}

(2)获取所有属性

unsigned int outCount;
Ivar * ivars = class_copyIvarList([self class], &outCount);
for (int i = 0; i < outCount; i ++) {
    Ivar ivar = ivars[i];
    NSString * name = [NSString stringWithUTF8String:ivar_getName(ivar)];
}

(3)得到方法列表class_copyMethodList

3,方法替换(method swizzling)

//newFoo将要替换的函数,oldFoo被替换的函数
//获取方法的实现
IMP newImp = class_getMethodImplementation([self class], @selector(newFoo));
//动态添加方法
class_addMethod(Class, @selector(newFoo), newImp, types);
//动态替换方法实现
class_replaceMethod(peopleClass, @selector(oldFoo), newImp, types);

method swizzling需要写在load方法里面(load调用时机是被在到runtime时,只调用一次,可以看看runtime源码)

上一篇 下一篇

猜你喜欢

热点阅读