objc 运行时

运行时,就是运行时候的一些事儿。

 

语言相关的运行时系统相当于 该语言的一种特殊的操作系统,所以我们应该了解 Objective-C runtime system 的基本原理 和 我们能够怎样去利用ObjC runtime system。

 

Objc 中,消息直到运行的时候才和方法实现进行绑定的。但编译器会把一个消息表达式 转化为一个对消息函数 objc_msgSend 的调用:

1. 编译阶段

[receiver  message];

转化为:objc_msgSend(receiver,  selector, arg1, argf2, …)

 

2. 运行阶段

     objc_msgSend 完成如下:

 

    First , finds  the  procedure (method implementation)that the selector refers to.

 

     Then, calls the procedure, passing it the  receiving object (a point to its data), along with any arguments。

 

      Pass  the return value of the procedure as its own return value.

 

 

This is the way that method implementations are chosen at runtime  -  or, in the jargon of object-oriented programming, that methods are dynamically bound to messages.

 

绕过动态绑定的唯一方法是 找到某个method 的地址,然后像 函数一样地直接调用,比如当 setFilled: 方法被调用多次时候,讲采用如下的形式:

void (*setter)(id, SEL, BOOL);

setter = (void(*)(id, SEL, BOOL)) [target  methodForSelector:@selector(setFilled:)];

for (int i=0; i<1000; i++) {

            setter(targetList[i],  @selector(setFilled:), YES);

}

 

The first two arguments passed to the procedure are the receiving object (self) and the method selector (_cmd). These arguments are hidden in method syntax but must be made explicit when the method is called as a function.

posted @ 2012-06-18 15:11  姜萌芽  阅读(483)  评论(0编辑  收藏  举报