iOS isa 浅析

  看见一到面试题讲述一下Objective-C中的isa?完全没听说过,打算小研究一下。

  参考:http://blog.sina.com.cn/s/blog_7a2ffd5c01010nme.html

  原来isa类似类似于java中的class,用于动态的获取一个类动态运行时的信息。不过OC比java牛B的是,OC可以在运行时为类添加方法,所以isa比class稍微复杂一点。

  看一下NSObject类的.h  

1 @interface NSObject <NSObject> {
2     Class isa  OBJC_ISA_AVAILABILITY;
3 }

  NSObject类作为所有OC对象的父类只有这一个属性isa,我们有必要研究一下,它究竟是什么。

  官方介绍是这样的:

  Every object is connected to the run-time system through its isa instance variable, inherited from the NSObject class. isa identifies the object's class; it points to a structure that's compiled from the class definition. Through isa, an object can find whatever information it needs at runtime such as its place in the inheritance hierarchy, the size and structure of its instance variables, and the location of the method implementations it can perform in response to messages.

  可见,通过一个实例对象(Object)的isa,我们可以找到一个对象的所以信息,如类属性的结构,类方法(消息)的入口地址等。

 

  我们再来看一下Class类

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;
/* Use `Class` instead of `struct objc_class *` */

  我们发现,objc_class结构体中,还有一个Class属性,它是什么作用呢?对象的类(Class)的isa指向了metaclass。通过它我们可以找到静态变量和方法,还有在这个类里动态添加的类别方法。

  Object-C对类对象与实例对象中的 isa 所指向的类结构作了不同的命名:类对象中的 isa 指向类结构被称作 metaclass,metaclass 存储类的static类成员变量与static类成员方法(+开头的方法);实例对象中的 isa 指向类结构称作 class(普通的),class 结构存储类的普通成员变量与普通成员方法(-开头的方法)。

原文地址:https://www.cnblogs.com/treejohn/p/3594157.html