iOS里方法调用不同于C/C++或其他语言,iOS方法调用形式是[reciver message],reciver是一个对象,但是这并不是马上执行reciver对象的message方法,而是向reciver对象发送一条message消息,1、这条消息可能由对象reciver来处理,2、也可能由转发给其他对象来处理,3、也可能假装没收到这条消息而没有处理。
其实[reciver message]被编译器转化为:id objc_msgSend(id self, SEL op, ...);
记录下objc_msgSend具体是如何发送消息的:
1、首先根据reciver对象的isa指针获取它对应的class;
2、优先在class的cache查找message方法,如果找不到,再到methodLists查找;
3、如果没有在class找到,再到super_class查找;
4、一旦找到message这个方法,就执行它实现的IMP。
[reciver message]调用方法时,如果在messge方法在reciver对象的类继承体系中没有找到方法,一般情况下程序就会crash掉,unrecognized selector sent to...类似。Objective-C运行时runtime机制下,在抛出异常之前,还有三次机会按以下顺序拯救程序,所以我们可以用runtime拯救找不到方法的时候。
1、Method Resolution ->resolveInstanceMethod 可以class_addMethod添加方法
2、Fast Forwarding ->forwardingTargetForSelector
3、Normal Forwarding ->methodSignatureForSelector、forwardInvocation
借鉴:点击打开链接