美文网首页
iOS 消息发送机制

iOS 消息发送机制

作者: 熊啊熊啊熊 | 来源:发表于2019-08-21 14:26 被阅读0次

通过前篇知道了,消息发送最后会来到这里。整体实现是下面这样:

IMP _class_lookupMethodAndLoadCache3(id obj, SEL sel, Class cls)
{
    return lookUpImpOrForward(cls, sel, obj, 
                              YES/*initialize*/, NO/*cache*/, YES/*resolver*/);
}
IMP lookUpImpOrForward(Class cls, SEL sel, id inst, 
                       bool initialize, bool cache, bool resolver)
{
    IMP imp = nil; //方法实现地址
    bool triedResolver = NO; //是否尝试了方法解析

    runtimeLock.assertUnlocked();

    // Optimistic cache lookup
    if (cache) {
        imp = cache_getImp(cls, sel);
        if (imp) return imp;
    }

    runtimeLock.lock(); 
    checkIsKnownClass(cls); //检查是否是已知类,如果是false则会抛出错误

    // 下面是对类的一个初始化
    
    if (!cls->isRealized()) {
        realizeClass(cls);
    }
    if (initialize  &&  !cls->isInitialized()) {
        runtimeLock.unlock();
        _class_initialize (_class_getNonMetaClass(cls, inst));
        runtimeLock.lock();
        // If sel == initialize, _class_initialize will send +initialize and 
        // then the messenger will send +initialize again after this 
        // procedure finishes. Of course, if this is not being called 
        // from the messenger then it won't happen. 2778172
    }

    
 retry:    
    runtimeLock.assertLocked();

    // Try this class's cache.
    // 缓存获取imp
    imp = cache_getImp(cls, sel);
    if (imp) goto done;

    // Try this class's method lists.
    {
        Method meth = getMethodNoSuper_nolock(cls, sel);
        if (meth) {
            log_and_fill_cache(cls, meth->imp, sel, inst, cls);
            imp = meth->imp;
            goto done;
        }
    }

    // Try superclass caches and method lists.
    {
        unsigned attempts = unreasonableClassCount();
        for (Class curClass = cls->superclass;
             curClass != nil;
             curClass = curClass->superclass)
        {
            // Halt if there is a cycle in the superclass chain.
            if (--attempts == 0) {
                _objc_fatal("Memory corruption in class list.");
            }
            
            // Superclass cache.
            imp = cache_getImp(curClass, sel);
            if (imp) {
                if (imp != (IMP)_objc_msgForward_impcache) {
                    // Found the method in a superclass. Cache it in this class.
                    log_and_fill_cache(cls, imp, sel, inst, curClass);
                    goto done;
                }
                else {
                    // Found a forward:: entry in a superclass.
                    // Stop searching, but don't cache yet; call method 
                    // resolver for this class first.
                    break;
                }
            }
            
            // Superclass method list.
            Method meth = getMethodNoSuper_nolock(curClass, sel);
            if (meth) {
                log_and_fill_cache(cls, meth->imp, sel, inst, curClass);
                imp = meth->imp;
                goto done;
            }
        }
    }

    // No implementation found. Try method resolver once.

    if (resolver  &&  !triedResolver) {
        runtimeLock.unlock();
        _class_resolveMethod(cls, sel, inst);
        runtimeLock.lock();
        // Don't cache the result; we don't hold the lock so it may have 
        // changed already. Re-do the search from scratch instead.
        triedResolver = YES;
        goto retry;
    }

    // No implementation found, and method resolver didn't help. 
    // Use forwarding.

    imp = (IMP)_objc_msgForward_impcache;
    cache_fill(cls, sel, imp, inst);

 done:
    runtimeLock.unlock();

    return imp;
}

1.首先主要看这一段

流程:
1.先在当前类缓存中查找, 没有找到则去当前类的方法列表中查找,找到直接返回,找到将方法存储到cache中
2.如果找不到则通过isa找到父类,在父类的cache里面查找,找不到则在父类的方法列表中查找,找到直接返回,找到将方法存储到cache中
3.一直找到循环3
4.如果一直到不到则进入动态方法解析


------------------- 1. 当前类方法中查找 --------------------

    // 在缓存中查找
    imp = cache_getImp(cls, sel);
    //如果找到就直接返回函数的IMP
    if (imp) goto done;
    //2.在这个类的方法列表里面寻找
    // Try this class's method lists.
    {
        //查找方法
        Method meth = getMethodNoSuper_nolock(cls, sel);
        if (meth) {
        //存储方法到缓存中
            log_and_fill_cache(cls, meth->imp, sel, inst, cls);
            imp = meth->imp;
            goto done;
        }
    }
    
    
    
    ----------------- 2. 父类查找 --------------------
    
    
    // Try superclass caches and method lists.
    {
    // 循环在父类里面查找
        unsigned attempts = unreasonableClassCount();
        for (Class curClass = cls->superclass;
             curClass != nil;
             curClass = curClass->superclass)
        {
            // Halt if there is a cycle in the superclass chain.
            if (--attempts == 0) {
                _objc_fatal("Memory corruption in class list.");
            }
            
            //父类的cache中查找
            imp = cache_getImp(curClass, sel);
            if (imp) {
                if (imp != (IMP)_objc_msgForward_impcache) {
                    // Found the method in a superclass. Cache it in this class.
                    log_and_fill_cache(cls, imp, sel, inst, curClass);
                    goto done;
                }
                else {
                    // Found a forward:: entry in a superclass.
                    // Stop searching, but don't cache yet; call method 
                    // resolver for this class first.
                    break;
                }
            }
            
            //父类方法列表中查找
            Method meth = getMethodNoSuper_nolock(curClass, sel);
            if (meth) {
            //找到存储到当前类的cache中
                log_and_fill_cache(cls, meth->imp, sel, inst, curClass);
                imp = meth->imp;
                goto done;
            }
        }
    }
    

动态方法解析

动态方法解析可以看到 triedResolver = YES, goto retry;发现代码还会再次走一遍消息查找上面的流程,由于triedResolver = YES所以不会再进入动态方法解析

// No implementation found. Try method resolver once.

//resolver == YES 是传参过来的
// triedResolver刚进来的时候是NO
    if (resolver  &&  !triedResolver) {
        runtimeLock.unlock();
        _class_resolveMethod(cls, sel, inst);
        runtimeLock.lock();
        // Don't cache the result; we don't hold the lock so it may have 
        // changed already. Re-do the search from scratch instead.
        triedResolver = YES;
        goto retry;
    }

2.动态方法解析会调用当前类的下面的方法
在方法里面动态添加方法就不会class_addMethod,就会进入到添加方法的这个里面

//对象方法进入
+ (BOOL)resolveClassMethod:(SEL)sel {
    //在这里动态添加方法
// 第一个参数是object_getClass(self)
class_addMethod(object_getClass(self), sel, (IMP)c_other, "v16@0:8");
    return [super resolveClassMethod:sel];
}

//类方法
+ (BOOL)resolveInstanceMethod:(SEL)sel {
    //在这里动态添加方法
    return [super resolveInstanceMethod:sel];
}

3.消息转发
消息转发会进入下面三个方法:

1.判断是否调用forwardingTargetForSelector 方法,如果该方法返回消息转发的接受者A,然后对返回的消息接受者发送消息objc_msgSend(A,SEL),如果没有返回则进行下一步
2.查看是否调用methodSignatureForSelector,如果调用,则返回NSMethodSignature这个类的对象,对象里面填写方法的参数编码(例如[a test]: v16@0:8),并且还要实现forwardInvocation这个方法,如果没有实现forwardInvocation,则跳转到最后调用doesNotRecognizeSelector报没有找到方法的错,如果实现了forwardInvocation,则不会报错,还可以拿到调用方法的接受者,参数,返回值

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

-(NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
    
    return [super methodSignatureForSelector:aSelector];
}

-(void)forwardInvocation:(NSInvocation *)anInvocation {

     return [super forwardInvocation:anInvocation];
}

参考:Objective-C 消息发送与转发机制原理

热爱生活,记录生活!

相关文章

  • iOS面试题总结(二)

    iOS面试题(二) 消息发送和转发机制,SEL和IMP 消息发送转载自黄龙辉消息发送和消息转发机制 在Object...

  • IOS消息传递机制

    ios的消息传递机制分为三个阶段:消息发送阶段,动态解析阶段,消息转发阶段。 消息发送阶段: 当ios的对象调用方...

  • iOS开发 — 初识消息机制

    消息机制原理 iOS进程是一个活的循环(runtime), OC中调用方法的实质就是发送消息, 而消息机制的本质就...

  • iOS 消息发送、转发机制

    消息直到运行时才会与方法实现进行绑定(在OC中方法调用是一个消息发送的过程) OC中调用方法: [xiaoming...

  • iOS开发--广播通知

    iOS 提供了一种 "同步的" 消息通知机制,观察者只要向消息中心注册, 即可接受其他对象发送来的消息,消息发送者...

  • iOS 消息发送与转发详解

    iOS 消息发送与转发详解 iOS 消息发送与转发详解

  • 08.Objective-C 消息机制

    问题 消息机制的三个阶段 1.消息机制发送消息阶段-消息发送2.消息机制动态方法解析阶段 -动态解析3.消息机制消...

  • 关于runtime的一些简单理解

    1.消息发送OC:运行时机制,消息机制是运行时机制最重要的机制消息机制:任何方法调用,本质都是发送消息 SEL:方...

  • iOS 消息发送机制

    1.引入#import 2.消息发送的方法: objc_msgsend(对象,方...

  • iOS 消息发送、转发机制简述

    在obj-c中我们可以向一个实例发送消息,相当于c/c++ java中的方法调用,只不过在这儿是说发送消息,实例收...

网友评论

      本文标题:iOS 消息发送机制

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