返回

一探iOS 消息查找:叩响代码背后的秘密

IOS

iOS消息查找的幕后故事

作为iOS开发人员,我们每天都在使用消息查找来调用对象的方法。然而,您是否曾经想过消息查找是如何工作的呢?在本文中,我们将深入iOS消息查找的内部机制,揭开它的神秘面纱。

分析底层源码

为了理解消息查找的原理,我们可以分析底层源码。首先,我们需要使用clang将OC代码转化为C++源码。例如,我们可以使用以下命令将Person.h和Person.m文件转化为Person.cpp文件:

clang -rewrite-objc Person.h Person.m -o Person.cpp

转化的结果如下:

namespace std {
struct type_info {
  virtual ~type_info();
};
}
struct _objc_class {
  Class isa;
  Class superclass;
  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;
};
struct _objc_ivar {
  char *name;
  char *type;
  int offset;
};
struct _objc_method {
  SEL name;
  char *types;
  IMP imp;
};
struct _objc_cache {
  void *buckets;
  struct _objc_hashtable *cache_buckets;
  struct _objc_hashtable *methodLists;
  unsigned int methodCount;
  unsigned int protocolCount;
  struct _objc_protocol_list *protocols;
  unsigned int classSize;
  unsigned int rwSize;
  unsigned int flags;
};
struct _objc_method_list {
  struct _objc_method_list *next;
  unsigned int count;
  struct _objc_method *methods;
  unsigned int method_count;
};
struct _objc_protocol_list {
  struct _objc_protocol_list *next;
  const char *name;
  struct _objc_protocol *protocol;
};
struct _objc_property {
  const char *name;
  const char *attributes;
};
struct _objc_class_ro {
  unsigned int flags;
  unsigned int instanceStart;
  unsigned int instanceSize;
  unsigned int reserved;
};
struct _objc_super {
  struct _objc_class *receiver;
  struct _objc_class *super_class;
};
struct _prop_t {
  const char *name;
  const char *attributes;
};
struct _objc_method {
  SEL name;
  char *types;
  IMP imp;
};
struct _objc_property {
  const char *name;
  const char *attributes;
};
struct _objc_class {
  Class isa;
  Class superclass;
  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;
};
...

消息发送

在iOS中,消息发送是一种动态绑定的机制。这意味着在运行时,根据接收者的类型决定调用哪个方法。消息发送的过程如下:

  1. 编译器将消息发送编译为一个方法调用。
  2. 运行时系统将方法调用转换为一个sel_getName调用。
  3. sel_getName调用将方法选择器转换为一个字符串。
  4. 运行时系统搜索接收者的类及其父类,以查找与方法选择器匹配的方法。
  5. 如果找到匹配的方法,则调用该方法。

动态绑定

动态绑定允许我们在运行时选择要调用的方法。这使得我们可以编写出更加灵活和可重用的代码。例如,我们可以编写一个函数,该函数可以调用任何实现了某个协议的对象的方法。

总结

在本文中,我们探讨了iOS消息查找的内部机制。我们了解了如何分析底层源码,消息发送的过程,以及动态绑定的概念。通过这篇文章,您应该对iOS消息查找有一个全面的了解。