iOS日记3-方法调用、调配和消息转发机制

2017-02-09  本文已影响0人  Mcyboy007

一:知识

1.C语言的函数调用方式
静态绑定:编译期决定运行时所应调用的函数
2.OC的函数调用方式
动态绑定:底层,所有的方法都是普通的C函数,然而对象收到消息后,最后调用什么方法取决于运行期,甚至可以在程序运行时改变。

id returnValue = [someObject messageName:parameter];

someObject:接收者
messageName:选择子
把“messageName:parameter”称为“消息”
以上消息经过编译后,转化为如下方法:

void objc_msgSend(id self, SEL cmd, ...)

默认的前两个参数是self和cmd,这是所有“消息”都一样的。其中,_cmd表示当前调用方法。

PS:关于方法调用有一个有趣的例子:

 @implementation Son : Father
- (id)init
{
    self = [super init];
    if (self)
    {
        NSLog(@"%@", NSStringFromClass([self class]));
        NSLog(@"%@", NSStringFromClass([super class]));
    }
return self;
}
@end

第一个输出Son,第二个,也是Son。为什么?
在调用[super class]的时候,runtime会去调用objc_msgSendSuper方法,而不是objc_msgSend:

OBJC_EXPORT void objc_msgSendSuper(void /* struct objc_super *super, SEL op, ... */ )

/// Specifies the superclass of an instance. 
struct objc_super {
    /// Specifies an instance of a class.
    __unsafe_unretained id receiver;

    /// Specifies the particular superclass of the instance to message. 
#if !defined(__cplusplus)  &&  !__OBJC2__
    /* For compatibility with old objc-runtime.h header */
    __unsafe_unretained Class class;
#else
    __unsafe_unretained Class super_class;
#endif
    /* super_class is the first class to search */
};

在objc_msgSendSuper方法中,第一个参数是一个objc_super的结构体,这个结构体里面有两个变量,一个是接收消息的receiver,一个是 当前类的父类super_class。
objc_msgSendSuper的工作原理应该是这样的:从objc_super结构体指向的superClass父类的方法列表开始查找selector,找到后以objc->receiver去调用这个selector。注意,最后的调用者是objc->receiver,而不是super_class!
那么objc_msgSendSuper最后就转变成:

objc_msgSend(objc_super->receiver, @selector(class))

二:原理:

objc_msgSend在接收者所属的类中搜索其“方法列表”,一直沿着继承体向上查找:

使用这种办法的前提是:相关方法的实现代码已经写好了,只等着运行的时候动态插在类里面。例如,@dynamic属性的实现。

- (id)forwardingTargetForSelector:(SEL)selector;

直接使用这个方法,只需要改变消息调用的目标,使消息在新的目标上得以调用即可。但是这样实现与“备援接收者”方案等效,很少有人这么做。这一步比较实用的方式为:触发消息前,先以某种方式改变消息内容(如追加参数,改换选择子等)。

最后简单提一下“方法调配”。
类的方法列表会把选择子的名称映射到相关的方法实现上,这些方法均已函数指针的形式来表示,叫做IMP,原型如下:

id (* IMP)(id, SEL, ...)

OC的运行时系统提供了方法能够操作这张表,也就允许了开发人员在程序运行时“动态的修改”某些方法的实现。这些方法主要包括了:

void method_exchangeImplementations(Method m1, Method m2);
Method class_getInstanceMethod(Class aClass, SEL aSelector);
Method class_getClassMethod(Class aClass, SEL aSelector);

具体的使用方式,相关的资料很多,就不展开了。切勿滥用!

上一篇 下一篇

猜你喜欢

热点阅读