performSelector为什么不会报错呢
来源:10-10 面试题-类间组织关系的理解
慕用8453459
2019-07-10
如题,有点不明白
写回答
1回答
-
逆风
2019-10-22
我们一般调用方法时,例如[dog run],会判断Dog.h文件,是否声明- (void)run方法,否则会编译不通过,如果只有声明而没有在Dog.m文件实现时,则或出现unrecognized selector sent to instance xxxx错误。编译完成之后,实际上执行[dog run]会变成((id(*)(id, SEL))objc_msgSend)(dog, @selector(run))。
再看下performSelector的源码实现为:
+ (id)performSelector:(SEL)sel {
if (!sel) [self doesNotRecognizeSelector:sel];
return ((id(*)(id, SEL))objc_msgSend)((id)self, sel);
}
二者都是调用objc_msgSend方法,只是performSelector会跳过编译检查这一步骤,所以即使在Dog.h文件中没有声明- (void)run方法,也不会报错,这样我们可以通过这种方式调用很多私有API。
10
相似问题