欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

isa 究竟是什么

程序员文章站 2024-03-25 16:50:40
...

Objective-C对象的第一个成员变量,就是isa。

先来看看官方解释,再说一下个人理解。
Every object is connected to the run-time system through itsisa instance variable, inherited from the NSObject class.isa identifies the object's class; it points to a structurethat's compiled from the class definition. Through isa, anobject can find whatever information it needs at run timesuch asits place in the inheritance hierarchy, the size and structure ofits instance variables, and the location of the methodimplementations it can perform in response to messages.

一个对象(Object)的isa指向这个对象的类(Class),这个对象的类(Class)的isa指向了metaclass。这样,就可以找到相对应的静态方法和变量了。
Objective-C的运行时是动态的,它能让你在运行的时候添加方法或者删除方法以及使用反射。

类的实例对象的 isa 指向它的类;类的 isa 指向该类的 metaclass ;
类的 super_class 指向期父类,如果该类为根类则值为NULL ;
metaclass的 isa 指向根 metaclass ,如果该metaclass是根 metaclass 则指向自身;
metaclass 的 super_class 指向父 metaclass ,如果该 metaclass 是根 metaclass 则指向该 metaclass 对应的类;

// objc.h文件中
#if !OBJC_TYPES_DEFINED
/// An opaque type that represents an Objective-C class.
typedef struct objc_class *Class;

/// Represents an instance of a class.
struct objc_object {
    Class isa  OBJC_ISA_AVAILABILITY;
};

/// A pointer to an instance of a class.
typedef struct objc_object *id;
#endif

// NSObject.h文件中
@interface NSObject <NSObject> {
    Class isa  OBJC_ISA_AVAILABILITY;
}

// 打开 objc_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;