美文网首页
objective runtime reference

objective runtime reference

作者: jackjhu | 来源:发表于2015-08-31 22:57 被阅读84次

    前言###

    The principal runtime function is the one that sends messages
    runtime最主要的功能就是发送消息。

    名词解释

    IMP:Implementation method pointer,指向method具体实现的一个C函数指针,这个函数指针一般长这样:
    id (*IMP) (id self, SEL , ... )
    带自少两个参数,receiver和SEL,后文会具体解释。

    消息###

    在Objective-C中,消息(messages)是在runtime时才绑定到方法的具体IMP(method implementations)上。

    objc_msgSend(receiver, selector)
    

    我们在消息中的参数它也可以接受

    objc_msgSend(receiver, selector, arg1, arg2, ...)
    

    **objc_class: **消息主要依赖编译器为每个类和对象创建的结构,每个类的结构包含两个最重要的元素:

    • 一个指向superclass的指针(super_class)
    • 一个消息派发表(objc_method_list)

    objc_object: 每个对象被创建时,程序为它分配内存,同时实例变量(variables)被初始化,第一个参数就一个指向它的类结构(class structure)的指针,我们称它为isa,给了对象一条能访问到它的类结构以及它的父类们的路,这是消息转发的根本。

    Class.png

    虽然isa不是Objective-C语言本身严格要求的一部分,但为了与Objective-C runtime system 环境协同工作,对象需要isa指针。

    下面的插图消息怎样找对正确的seletor和对应的IMP。

    message_framework.png

    为了加速message的处理,runtime缓存了selectors,和方法的地址,一但程序预热好了缓存,几乎所有的消息都能命中缓存这样messaging仅仅只会比函调直接调用非常轻微的慢点。

    使用隐藏参数

    使用[receiver message]方式发送消息,objc_msgSend找到正确的方法实现IMP后,它会调用call该方法,将message中参数传给那个IMP(method implementation),并会传给它两个隐藏的参数:

    • 消息接受对象(receiving object)
    • 方法的selector(selector for the method)

    获取method的地址
    能避开动态绑定的唯一方法就是得到一个IMP的地址,直接call,就像一个C语言函数一样。

    通过在NSObject类中定义的methodForSelector:来获取IMP(implementation method)的地址。然后通过这个指针来调用方法。对于返回的函数指针类型你必须要做好正确的转换。

    如果IMP(method implementation)如C函数般被调用的话,你必须显示的将上文中的两个隐藏参数(id self, SEL _cmd)传给它。就像这样:

            Person *a=[Person new];
            [a printClass];
            
            //默认method方法需要接受这两个参数。
            void(*IMP)(id,SEL);
            IMP=(void(*)(id,SEL))[a methodForSelector:@selector(printClass)];
            for (int i=0; i<10; i++) {
                IMP(a,@selector(printClass));
            }
    

    动态的方法解析与转发

    在某些场景,你可能希望动态的提供某个method的实现。例如Objective-C在申明属性properties特性就提供了@synamic命令:
    @dynamic propertyName

    你可以实现resolveInstanceMethod:resolveClassMethod:来动态的为一个指定的实例或者类selector提供实现方法。

    一个Objective-C方法method(IMP)其实就是一个简单的C函数,带有至少两个参数(id self, SEL _cmd)。你可以通过class_addMethod方法给类添加方法。

    例如代码:

    ------------Person.h
    @interface Person : NSObject
    @property (nonatomic, strong) NSString *name;
    - (void)printClass;
    @end
    ------------Person.m
    @implementation Person
    @dynamic name;
    
    void dynamicNameIMP(id self,SEL _cmd) {
        NSLog(@"Message:--%@: NAME IS UNKNOWN !!!",NSStringFromSelector(_cmd));
    }
    
    + (BOOL)resolveInstanceMethod:(SEL)sel {
    //动态提供name属性的getter方法实现
        if (sel==@selector(name)) {
            class_addMethod([self class],sel,(IMP)dynamicNameIMP,"v@:");
            return YES;
        }
        return [super resolveInstanceMethod:sel];
    }
    
    ...
    
    @end
    
    转发消息

    - forwardingTargetForSelector:


    将一个seletor转给另一个对象处理。

    这个比较直接,举个栗子:

    ---------------------------Person.h
    @interface Person : NSObject
    @property (nonatomic, strong) NSString *name;
    - (void)doingHomework;
    @end
    ---------------------------Person.m
    #import "Person.h"
    #import "Student.h"
    #import <objc/message.h>
    
    @implementation Person
    - (id)forwardingTargetForSelector:(SEL)aSelector {
        if (aSelector==@selector(doingHomework)) {
            return [Student new];
        }
        return [super forwardingTargetForSelector:aSelector];
    }
    
    //- (void)doingHomework {}
    ...
    @end
    ---------------------------Student.h
    #import <Foundation/Foundation.h>
    
    @interface Student : NSObject
    - (void)doingHomework;
    @end
    ---------------------------Student.m
    #import "Student.h"
    
    @implementation Student
    - (void)doingHomework {
        NSLog(@"I am a student, I doing homework !!!");
    }
    @end
    

    然后在main.m中给person实例的发送doingHomework消息,得到I am a student, I doing homework !!!
    成功转发到Student类。

    - forwardInvocation:


    同样是消息转发,NSInvocation打包了消息信息。有更多的功能。

    示例代码,将上文中的forwardingTargetForSelector:替换为下面即可,两者都有的话,先调用forwardingTargetForSelector:.

    - (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
        NSMethodSignature *methodSignature=[super methodSignatureForSelector:aSelector];
        if (!methodSignature) {
            methodSignature=[Student instanceMethodSignatureForSelector:aSelector];
        }
        return methodSignature;
    }
    
    - (void)forwardInvocation:(NSInvocation *)anInvocation {
        SEL seletor=anInvocation.selector;
        Student *student=[Student new];
        if ([student respondsToSelector:seletor]) {
            [anInvocation invokeWithTarget:student];
        }
    }
    

    Category


    Category methods can do anything that methods defined in the class proper can do. At runtime, there’s no difference.

    相关文章

      网友评论

          本文标题:objective runtime reference

          本文链接:https://www.haomeiwen.com/subject/lzflcttx.html