iOS:消息機(jī)制淺析

說明 時(shí)間
首次發(fā)布 2017年08月09日
最近更新 2019年05月04日

消息機(jī)制可以認(rèn)為是objc_msgSend的執(zhí)行流程,包括消息發(fā)送、動(dòng)態(tài)方法解析和消息轉(zhuǎn)發(fā)。

一、消息發(fā)送

消息發(fā)送

二、動(dòng)態(tài)方法解析

  • 檢查是否曾經(jīng)有動(dòng)態(tài)解析
    • 有:消息轉(zhuǎn)發(fā)
    • 沒有:調(diào)用 + (BOOL)resolveInstanceMethod:(SEL)sel+ (BOOL)resolveClassMethod:(SEL)sel 來動(dòng)態(tài)解析,并將標(biāo)記置為YES。

注意:在動(dòng)態(tài)解析后,會(huì)重新回到 消息發(fā)送 的流程。

示例:

//MZPerson.h
#import <Foundation/Foundation.h>

@interface MZPerson : NSObject

- (void)sayHello;
- (void)sayWorld;

+ (void)unimplementationClassMethod;

@end


//MZPerson.m
#import "MZPerson.h"
#import <objc/runtime.h>

@implementation MZPerson

/**
 動(dòng)態(tài)添加方法之成員方法
 */
- (void)addByMethod {
    NSLog(@"%@--%s--%s", self, sel_getName(_cmd), __func__);
}

void addByFunction(id self, SEL _cmd) {
    NSLog(@"%@--%s--%s", self, sel_getName(_cmd), __func__);
}

+ (BOOL)resolveInstanceMethod:(SEL)sel {
    
    //通過C函數(shù)實(shí)現(xiàn)
    if (sel == @selector(sayHello)) {
        //types:類型編碼, v表示void, @表示id或NSObject*, :表示SEL. 這些都可以用@encode()查看
        class_addMethod(self, sel, (IMP)addByFunction, "v@:");
        
        //return YES/NO都是無所謂的,只是方便底層打印而已.但最好還是按規(guī)范來,YES表示添加了方法到接受者
        return YES;
    }
    
    //通過OC方法實(shí)現(xiàn)
    if (sel == @selector(sayWorld)) {
        Method method = class_getInstanceMethod(self, @selector(addByMethod));
        class_addMethod(self, sel, method_getImplementation(method), method_getTypeEncoding(method));
        return YES;
    }
    
    return [super resolveInstanceMethod:sel];
}

+ (BOOL)resolveClassMethod:(SEL)sel {
    //通過C函數(shù)實(shí)現(xiàn)
    if (sel == @selector(unimplementationClassMethod)) {
        //需要特別注意的是,類方法存放在元類里,所以這里要把方法添加到object_getClass(self)
        class_addMethod(object_getClass(self), sel, (IMP)addByFunction, "v@:");
        return YES;
    }
    return [super resolveClassMethod:sel];
}

@end

三、消息轉(zhuǎn)發(fā)

消息轉(zhuǎn)發(fā)分為兩個(gè)階段:
第一階段:- (id)forwardingTargetForSelector:(SEL)aSelector
第二階段:- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector- (void)forwardInvocation:(NSInvocation *)anInvocation;

當(dāng)階段一沒有實(shí)現(xiàn),或者返回nil的時(shí)候,則進(jìn)行階段二;如果消息轉(zhuǎn)發(fā)處理的是成員方法,那么三個(gè)階段都使用成員方法,否則就使用類方法。如代碼里所示。

消息轉(zhuǎn)發(fā)圖示
//消息轉(zhuǎn)發(fā)第一階段
//底層是通過`id cls = object_getClass(receiver);`拿到receiver
- (id)forwardingTargetForSelector:(SEL)aSelector {
    if (aSelector == @selector(sayHello)) {
//        //sayHello是對象方法,則返回的必須是一個(gè)對象,并且該對象中有成員方法sayHello
//        //返回nil,則直接進(jìn)入消息轉(zhuǎn)發(fā)的第二個(gè)階段
        return [GoodGuy new];
    }
    return [super forwardingTargetForSelector:aSelector];
}


//消息轉(zhuǎn)發(fā)第二階段(該部分是針對成員方法)
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {

    if (aSelector == @selector(sayHello)) {
        return [NSMethodSignature signatureWithObjCTypes:"v@:@q"];
    }
    return [super methodSignatureForSelector:aSelector];
}

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

    //可以用anInvocation里的selector; 也可以自己直接指定一個(gè)方法
    anInvocation.selector = @selector(offerHelp:age:);

    NSString *name = @"小紅";
    NSInteger age = 18;

    //每一個(gè)方法會(huì)默認(rèn)隱藏兩個(gè)參數(shù):self、_cmd,所以自定義參數(shù)要從下標(biāo)2開始
    [anInvocation setArgument:&name atIndex:2];
    [anInvocation setArgument:&age atIndex:3];

    GoodGuy *goodguy = [GoodGuy new];
    //做個(gè)判斷,保證指定的receiver會(huì)響應(yīng)該selector
    if ([goodguy respondsToSelector:anInvocation.selector]) {
        [anInvocation invokeWithTarget:goodguy];
    }
}

//以下是針對于類方法的消息轉(zhuǎn)發(fā)(區(qū)別只是將這兩個(gè)方法換成`+`即可)
//消息轉(zhuǎn)發(fā)第一階段
+ (id)forwardingTargetForSelector:(SEL)aSelector {
    if (aSelector == @selector(unimplementationClassMethod)) {
        
        //返回nil,則直接進(jìn)入消息轉(zhuǎn)發(fā)的第二個(gè)階段
        //消息轉(zhuǎn)發(fā)類方法,這里需要傳入一個(gè)類對象
        return [GoodGuy class];
    }
    return [super forwardingTargetForSelector:aSelector];
}

+ (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {

    if (aSelector == @selector(unimplementationClassMethod)) {
        //如果需要傳參,則ObjCTypes一定要寫寫清,不然在傳參時(shí)會(huì)報(bào)越界
        //如果需要進(jìn)行消息轉(zhuǎn)發(fā)給一個(gè)`無參無返回值`的方法,無論被轉(zhuǎn)發(fā)的selector是什么類型的,通通可以用@"v@:"來表示
        return [NSMethodSignature signatureWithObjCTypes:"v@:@q"];
    }
    return [super methodSignatureForSelector:aSelector];
}

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

    //可以用anInvocation里的selector; 也可以自己直接指定一個(gè)方法
    anInvocation.selector = @selector(offerHelp:age:);

    NSString *name = @"小紅";
    NSInteger age = 18;

    //每一個(gè)方法會(huì)默認(rèn)隱藏兩個(gè)參數(shù):self、_cmd,所以自定義參數(shù)要從下標(biāo)2開始
    [anInvocation setArgument:&name atIndex:2];
    [anInvocation setArgument:&age atIndex:3];

    GoodGuy *goodguy = [GoodGuy new];
    //做個(gè)判斷,保證指定的receiver會(huì)響應(yīng)該selector
    if ([goodguy respondsToSelector:anInvocation.selector]) {
        [anInvocation invokeWithTarget:goodguy];
    }
}

拓展

消息轉(zhuǎn)發(fā)還可以用于降低 unrecognized selector 的崩潰率。

示例:

#import <Foundation/Foundation.h>

@interface MZPerson : NSObject

- (void)printPerson:(NSString *)name age:(NSInteger)age;

@end

@implementation MZPerson

- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
    // 能響應(yīng)的直接走原先的邏輯
    if ([self respondsToSelector:aSelector]) {
        return [super methodSignatureForSelector:aSelector];
    }
    
    // 找不到的方法
    return [NSMethodSignature signatureWithObjCTypes:"v@:"];
}

// 找不到的方法,都會(huì)來到這里
- (void)forwardInvocation:(NSInvocation *)anInvocation {
    NSLog(@"找不到%@方法", NSStringFromSelector(anInvocation.selector));
}

@end


int main(int argc, const char * argv[]) {
    @autoreleasepool {
        MZPerson *person = [[MZPerson alloc] init];
        //MZPerson里并沒有實(shí)現(xiàn)`printPerson:age:`的方法
        [person printPerson:@"LynnZhang" age:12];
    }
    return 0;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
禁止轉(zhuǎn)載,如需轉(zhuǎn)載請通過簡信或評論聯(lián)系作者。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容