您的位置:首页 > 其它

函数调用和给对象发消息(Runtime理解)

2016-03-06 00:08 197 查看
在写代码的时候这个差距其实是不打看的出得,很多时候也就无所谓叫什么,很多人为了便于理解,干脆就叫函数调用。
这个其实应该是oc的一个特色,消息发送。
具体的类
typedef struct objc_class *Class;
typedef struct objc_object {
Class isa;
} *id;
typedef struct objc_selector   *SEL;
typedef id (*IMP)(id, SEL, ...);

类结构
struct objc_class {

**struct** objc_class

**super_class;        /*父类*/**

const char *name;                     **/***类名字*/

long version;         **                  /***版本信息*/

long info;                                  **/***类信息*/

long instance_size;                   **/***实例大小*/

**struct** objc_ivar_list *ivars;   **  /***实例参数链表*/

**struct** objc_method_list **methodLists; ** /*方法链表*/**

**struct** objc_cache *cache;               **/***方法缓存*/

**struct** objc_protocol_list *protocols;  ** /*协议链表*/**

};

在这个methodLists中是一个方法的list
typedef struct objc_method *Method;

typedef struct objc_ method {

**SEL method_name;//方法名称**

**char *method_types;//方法参数类型**

**IMP method_imp;//方法实现的函数指针**

};

当你发送消息时,首先回去找它对应的方法list,找到后就会使用相应的方法。
大致是这样的流程,当然细节也很多
1,它首先找到 SEL 对应的方法实现 IMP。因为不同的类对同一方法可能会有不同的实现,所以找到的方法实现依赖于消息接收者的类型。
2, 然后将消息接收者对象(指向消息接收者对象的指针)以及方法中指定的参数传递给方法实现 IMP。
3, 最后,将方法实现的返回值作为该函数的返回值返回。

starain Dou 豆电雨

文/natewang(简书作者)
原文链接:http://www.jianshu.com/p/ca70bfb142da
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: