iOS 消息轉(zhuǎn)發(fā)機(jī)制(實(shí)現(xiàn)多繼承)

我們都知道在Objective-C中,對(duì)象調(diào)用方法實(shí)際上是在發(fā)消息,當(dāng)對(duì)象接收到一條消息時(shí),消息函數(shù)隨著對(duì)象isa指針到類的結(jié)構(gòu)體中,在method list中查找方法selector。如果在本類中找不到對(duì)應(yīng)的selector,則objc_msgSend會(huì)向其父類的method list中查找selector,如果還不能找到則沿著繼承關(guān)系一直向上查找,直到找到NSObject類。

如果一直查找到根類仍舊沒有實(shí)現(xiàn),則嘗試進(jìn)行消息轉(zhuǎn)發(fā)。消息轉(zhuǎn)發(fā)分為三步:

  • 第一步 動(dòng)態(tài)方法解析

調(diào)用resolveInstanceMethod:方法 (或 resolveClassMethod:)。允許用戶在此時(shí)為該 Class 動(dòng)態(tài)添加實(shí)現(xiàn)。如果有實(shí)現(xiàn)了,則調(diào)用并返回YES,那么重新開始objc_msgSend流程。這一次對(duì)象會(huì)響應(yīng)這個(gè)選擇器,一般是因?yàn)樗呀?jīng)調(diào)用過class_addMethod。如果仍沒實(shí)現(xiàn),繼續(xù)下面的動(dòng)作。

  • 第二步 快速轉(zhuǎn)發(fā)(消息轉(zhuǎn)發(fā)重定向)

調(diào)用forwardingTargetForSelector:方法,嘗試找到一個(gè)能響應(yīng)該消息的對(duì)象。如果獲取到,則直接把消息轉(zhuǎn)發(fā)給它,返回非 nil 對(duì)象。否則返回 nil ,繼續(xù)下面的動(dòng)作。注意,這里不要返回 self ,否則會(huì)形成死循環(huán)。

  • 第三步 完整消息轉(zhuǎn)發(fā)
    • 調(diào)用methodSignatureForSelector:方法,嘗試獲得一個(gè)方法簽名。如果獲取不到,則直接調(diào)用doesNotRecognizeSelector拋出異常。如果能獲取,則返回非nil創(chuàng)建一個(gè) NSlnvocation 并傳給forwardInvocation:。

    • 調(diào)用forwardInvocation:方法,將第3步獲取到的方法簽名包裝成 Invocation 傳入,如何處理就在這里面了,并返回非nil。

  • 最后

調(diào)用doesNotRecognizeSelector:,默認(rèn)的實(shí)現(xiàn)是拋出異常。如果第3步?jīng)]能獲得一個(gè)方法簽名,執(zhí)行該步驟。


消息轉(zhuǎn)發(fā)的實(shí)際應(yīng)用

第一步 動(dòng)態(tài)方法解析
// 消息轉(zhuǎn)發(fā)第一步 動(dòng)態(tài)方法解析(其實(shí)不是轉(zhuǎn)發(fā),是動(dòng)態(tài)添加方法)
+ (BOOL)resolveInstanceMethod:(SEL)sel{
    NSString *selName = NSStringFromSelector(sel);

     // 此處可根據(jù)情況作出需要的判斷,需要給哪些方法做處理
    if ([selName hasPrefix:@"eat"]) {
        class_addMethod([self class], sel, (IMP)shouldDoSomeThing, "v@:");
        return YES;
    }
    return [super resolveInstanceMethod:sel];
}

void shouldDoSomeThing(id self ,SEL _cmd) {
    NSLog(@"class:%@, sel:%s",self,sel_getName(_cmd));
    NSLog(@"差不多也該干點(diǎn)啥");
}

如果沒有實(shí)現(xiàn)第一步,系統(tǒng)會(huì)繼續(xù)進(jìn)行第二步查找,進(jìn)行快速轉(zhuǎn)發(fā)

第二步 快速轉(zhuǎn)發(fā)(消息轉(zhuǎn)發(fā)重定向)
// 消息轉(zhuǎn)發(fā)第二步 轉(zhuǎn)發(fā)給備選接收者
- (id)forwardingTargetForSelector:(SEL)aSelector{
    if ([HitTestView instancesRespondToSelector:aSelector]) {
        return [HitTestView new];
    }
    
    return [super forwardingTargetForSelector:aSelector];
}

如果沒有實(shí)現(xiàn)第二步,系統(tǒng)會(huì)繼續(xù)進(jìn)行第三步查找,進(jìn)行完整消息轉(zhuǎn)發(fā)

  • 第三步 完整消息轉(zhuǎn)發(fā)
//消息轉(zhuǎn)發(fā)第三步 完整的消息轉(zhuǎn)發(fā)
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector{
    NSMethodSignature *signature = [super methodSignatureForSelector:aSelector];
    if (!signature) {
        //不簽名會(huì)崩潰,以下兩種獲取方法簽名的方式皆可

        // 1. 判斷實(shí)現(xiàn)類的實(shí)例是否有這個(gè)方法 有則簽名這個(gè)方法 保證能正確轉(zhuǎn)發(fā)
//        if ([TestObject instancesRespondToSelector:aSelector]) {
//            signature = [TestObject instanceMethodSignatureForSelector:aSelector];
//        }
        // 2. 直接簽名
        if ([NSStringFromSelector(aSelector) hasPrefix:@"eat"]) {
            signature = [NSMethodSignature signatureWithObjCTypes:"v@:"];
        }
    }
    
    return signature;
}

- (void)forwardInvocation:(NSInvocation *)anInvocation{
    if ([TestObject instancesRespondToSelector:anInvocation.selector]) {
        [anInvocation invokeWithTarget:[TestObject new]];
    }
}

至此,若沒有實(shí)現(xiàn)以上三步,調(diào)用doesNotRecognizeSelector:,拋出異常。

注:類型編碼:"v@:"
v -> void 表示無返回值
@ -> object 表示id參數(shù)(self)
: -> method selector 表示SEL
"v@:@":表示傳入一個(gè)參數(shù),無返回值


消息轉(zhuǎn)發(fā)+Protocol實(shí)現(xiàn)多繼承

現(xiàn)有 MultiInheritA 、 MultiInheritB 、 MultiInheritC 這三個(gè)類,讓C繼承A也繼承B的方法。

先看 MultiInheritA

#import <Foundation/Foundation.h>

@protocol MultiInheritAProtocol <NSObject>

- (void)goToSchool;

@end

@interface MultiInheritA : NSObject<MultiInheritAProtocol>

@end

#import "MultiInheritA.h"

@implementation MultiInheritA

- (void)goToSchool {
    NSLog(@"MultiInheritA goToSchool");
}

@end



再看 MultiInheritB

#import <Foundation/Foundation.h>

@protocol MultiInheritBProtocol <NSObject>

- (void)goHome;

@end

@interface MultiInheritB : NSObject <MultiInheritBProtocol>

@end
#import "MultiInheritB.h"

@implementation MultiInheritB

- (void)goHome {
    NSLog(@"MultiInheritB goHome");
}

@end


重點(diǎn)是這個(gè) MultiInheritC

#import <Foundation/Foundation.h>
#import "MultiInheritA.h"
#import "MultiInheritB.h"

@interface MultiInheritC : NSObject<MultiInheritAProtocol,MultiInheritBProtocol>

@end
#import "MultiInheritC.h"


@interface MultiInheritC()

@property (nonatomic,strong) MultiInheritA *myA;
@property (nonatomic,strong) MultiInheritB *myB;

@end

@implementation MultiInheritC

- (MultiInheritA *)myA {
    if (_myA == nil) {
        _myA = [MultiInheritA new];
    }
    return _myA;
}

- (MultiInheritB *)myB {
    if (_myB == nil) {
        _myB = [MultiInheritB new];
    }
    return _myB;
}

- (id)forwardingTargetForSelector:(SEL)aSelector {
    if ([self.myA respondsToSelector:aSelector]) {
        return self.myA;
    }
    else if ([self.myB respondsToSelector:aSelector]) {
        return self.myB;
    }
    return self;
}

@end
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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