引用Cocoa with Love
每个对象都有一个类。这是一个基本的面向对象概念,但在 Objective-C 中,它也是数据的基本部分。任何在正确位置具有指向类的指针的数据结构都可以被视为对象。在 Objective-C 中,一个对象的类是由它的isa
指针决定的。isa
指针指向对象的类。
作为一个证明,这里是id
作为指向objc_object
结构的指针的声明。
typedef struct objc_object {
Class isa;
} *id;
所以这里我们说到点子上了。什么是Class
?
我们来看看定义
Class
定义如下(实际上可能会因运行时而异,但让我们保持简单)
struct objc_class {
Class isa;
}
typedef struct objc_class *Class;
如您所见, aClass
也有一个isa
指针。它看起来很像objc_object
定义,原因很简单:Class
实际上是一个对象。
但是 a 的类别是Class
什么?它 - 根据定义 - 一个元类。
根据同一来源(以粗体显示直接解决您的问题的部分),
元类和Class
之前的一样,也是一个对象。这意味着您也可以在其上调用方法。当然,这意味着它也必须有一个类。
所有元类都使用基类的元类(Class
继承层次结构中最顶层的元类)作为它们的类。这意味着对于从NSObject
(大多数类)派生的所有类,元类将NSObject
元类作为其类。
Following the rule that all meta-classes use the base class' meta-class as their class, any base meta-classes will be its own class (their isa pointer points to themselves). This means that the isa pointer on the NSObject
meta-class points to itself (it is an instance of itself).
For further reading on the subject, here's another great explanation by Greg Parker.