instancesRespondToSelector與respondsToSelector的區別

最近團隊在研究Aspects庫中發現了一點疑惑,即以下圖所示爲何要有respondsToSelector和instancesRespondToSelector兩個判斷?:blog

因此咱們查看了一下objc中關於這兩個方法的實現:get

+ (BOOL)instancesRespondToSelector:(SEL)sel {
    if (!sel) return NO;
    return class_respondsToSelector(self, sel);
}

+ (BOOL)respondsToSelector:(SEL)sel {
    if (!sel) return NO;
    return class_respondsToSelector_inst(object_getClass(self), sel, self);
}

- (BOOL)respondsToSelector:(SEL)sel {
    if (!sel) return NO;
    return class_respondsToSelector_inst([self class], sel, self);
}

 而後加以實踐it

@interface Test : NSObject

- (void)objectFun;

+ (void)classFun;

@end

 

BOOL flag;
    
flag = [Test instancesRespondToSelector:@selector(objectFun)]; //YES
    
flag = [Test instancesRespondToSelector:@selector(classFun)]; //NO
    
flag = [Test respondsToSelector:@selector(objectFun)]; //NO
    
flag = [Test respondsToSelector:@selector(classFun)]; //YES
    
Test *obj = [[Test alloc] init];
flag = [obj respondsToSelector:@selector(objectFun)]; //YES
    
flag = [obj respondsToSelector:@selector(classFun)]; //NO

 因此咱們能夠看出:class

【1】instancesRespondToSelector只是類方法,respondsToSelector有類方法和實例方法兩種實現object

【2】 [類 instancesRespondToSelector]判斷的是該類是否包含某實例方法,等效於:[該類的實例 respondsToSelector]。select

【3】 [類 respondsToSelector]用於判斷是否包含某個類方法,[該類的實例 respondsToSelector]用於判斷該實例是否包含某個實例方法。方法

 

也就是Aspects庫中實現瞭如下對比im

相關文章
相關標籤/搜索