iOS中類找不到方法時消息處理機制

如果我們調用了一個類沒有的方法,就會進入消息處理機制,有下面幾個階段

  1. “動態方法解析”:
    + (BOOL)resolveClassMethod:(SEL)sel;
    + (BOOL)resolveInstanceMethod:(SEL)sel;
    征詢接收者所屬的類,是否需要動態添加類方法或實例方法,來處理這個未找到的方法。
    1). 首先判斷是否實現了 resolveInstanceMethod,如果沒有實現,進入下一步處理;
    2). 如果實現了,調用 resolveInstanceMethod,獲取返回值;
    3). 如果返回值為 YES,表示 resolveInstanceMethod 聲稱它已經提供了 selector 的實現,因此再次查找 method list,如果找到對應的 IMP,則返回該實現,否則提示警告信息,進入下一步處理;
    4). 如果返回值為 NO,進入下一步處理;

  2. “重定向”:
    - (id)forwardingTargetForSelector:(SEL)aSelector;
    如果沒有動態添加方法,則會進入此階段,此時詢問是否要將這條消息轉發給其他的對象,來處理這個方法。如果返回nil,即表示不轉發給其他對象,此時會進入第3階段

  3. “消息轉發”:
    - (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector;
    - (void)forwardInvocation:(NSInvocation *)anInvocation;
    此時系統會根據SEL詢問方法簽名,即調用methodSignatureForSelector:方法獲取方法簽名,如果這個方法返回nil,那么就會看到我們最常見的一種crash -[Class xxx]: unrecognized selector sent to instance ...
    如果這個方法返回了正確的方法簽名,系統就會根據消息的SEL、target、參數、方法簽名,把消息封裝成一個NSInvocation對象,我們可以拿到這個NSInvocation對象,指定對應的target調用方法。
    這里可以不調用Invocation,并不會觸發crash

1.動態解析

下面我們通過一個demo來理解下動態解析,新建一個Person的類

//Person.h
@interface Person : NSObject
//在.m文件中添加了@dynamic,所以不會自動添加setter和getter方法
@property(assign,nonatomic)NSInteger weight;
@end

//Person.m
@implementation Person
@dynamic weight;

void setPropertyDynamic(id self,SEL _cmd){    
    NSLog(@"This is a dynamic method added for Person instance");
}

+ (BOOL)resolveInstanceMethod:(SEL)sel{    
    if (sel == @selector(setWeight:)){
        class_addMethod([self class], sel,(IMP)setPropertyDynamic, "v@:");
        return YES;
    }
    return [super resolveInstanceMethod:sel];
}
@end

// main函數中調用
Person *p = [[Person alloc]init] ;
p.weight = 100;

上面的例子,會打印出log:This is a dynamic method added for Person instance

2.重定向

再來通過demo理解重定向,Person類和上面一樣,再建一個People類

//Person.m

// Person類重寫重定向方法,將weight的getter方法重定向到People類,其他方法不處理
- (id)forwardingTargetForSelector:(SEL)aSelector{
    if (aSelector == @selector(weight)) {
        People *people = [People new];
        return people;
    }
    id target = [super forwardingTargetForSelector:aSelector];
    return target;
}

//People.h
@interface People : NSObject
@end

//People.m
@implementation People
- (NSInteger)weight {
    return 666;
}
@end

// main函數中調用
Person *person = [[Person alloc] init] ;
NSInteger weightValue = person.weight;
NSLog(@"%ld",weightValue); //666

上面的例子,會打印出log:666

3.消息轉發

再來通過demo理解消息轉發,Person類、People類和上面一樣

//Person.h
//在.m文件中添加了@dynamic,所以下面的屬性不會自動添加setter和getter方法
@property(copy,nonatomic)NSString *identifier;


//Person.m
@dynamic identifier;

- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
{
    if (aSelector == @selector(setIdentifier:) || aSelector == @selector(identifier) ) {
        NSMethodSignature *sign = [People instanceMethodSignatureForSelector:aSelector];
        return sign;
    }
    return nil;
}
- (void)forwardInvocation:(NSInvocation *)anInvocation{
    People *people = [[People alloc]init];
    if ([people respondsToSelector:[anInvocation selector]]) {
        [anInvocation invokeWithTarget:people];
    }else{
        [super forwardInvocation:anInvocation];
    }
}


//People.h
@property(copy,nonatomic)NSString *identifier;


// main函數中調用
Person *person = [[Person alloc] init];
person.identifier = @"yzk whlpkk";
NSLog(@"%@",person.identifier); //null

上面的例子,會打印出log:(null),之所以會這樣,是因為我們消息轉發的時候,每次都實例化了一個新的people,所有我們setter的people和getter的people并不是同一個實例。

再來說一下消息轉發和重定向的區別。

  1. 重定向只能重定向到一個對象,但是消息轉發,可以同時對多個對象轉發,只需要[anInvocation invokeWithTarget:]多個target即可。
  2. 重定向的target必須要有一個,如果是nil,則target就是當前實例。消息轉發
    可以不轉發,即不調用[anInvocation invokeWithTarget:],不會crash,但是消息轉發的methodSignatureForSelector:方法簽名不能返回nil,否則會crash。

最后附上demo

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容