iOS Runtime详解(新手也看得懂)

2020-01-21 07:51:57刘景俊


OBJC_EXPORT id objc_msgSend(id self, SEL op, ...)

那消息传递是怎么实现的呢?我们看看对象(object),类(class),方法(method)这几个的结构体:


//对象
struct objc_object {
 Class isa OBJC_ISA_AVAILABILITY;
};
//类
struct objc_class {
 Class isa OBJC_ISA_AVAILABILITY;
#if !__OBJC2__
 Class super_class     OBJC2_UNAVAILABLE;
 const char *name      OBJC2_UNAVAILABLE;
 long version      OBJC2_UNAVAILABLE;
 long info      OBJC2_UNAVAILABLE;
 long instance_size     OBJC2_UNAVAILABLE;
 struct objc_ivar_list *ivars    OBJC2_UNAVAILABLE;
 struct objc_method_list **methodLists   OBJC2_UNAVAILABLE;
 struct objc_cache *cache     OBJC2_UNAVAILABLE;
 struct objc_protocol_list *protocols   OBJC2_UNAVAILABLE;
#endif
} OBJC2_UNAVAILABLE;
//方法列表
struct objc_method_list {
 struct objc_method_list *obsolete   OBJC2_UNAVAILABLE;
 int method_count      OBJC2_UNAVAILABLE;
#ifdef __LP64__
 int space      OBJC2_UNAVAILABLE;
#endif
 /* variable length structure */
 struct objc_method method_list[1]   OBJC2_UNAVAILABLE;
}        OBJC2_UNAVAILABLE;
//方法
struct objc_method {
 SEL method_name      OBJC2_UNAVAILABLE;
 char *method_types     OBJC2_UNAVAILABLE;
 IMP method_imp      OBJC2_UNAVAILABLE;
}
  1. 系统首先找到消息的接收对象,然后通过对象的isa找到它的类。
  2. 在它的类中查找method_list,是否有selector方法。
  3. 没有则查找父类的method_list。
  4. 找到对应的method,执行它的IMP。
  5. 转发IMP的return值。

下面讲讲消息传递用到的一些概念: