Metaclass - in Objective-C

In Objective-C

The following information is accurate for the Cocoa framework.

Metaclasses in Objective-C are almost the same as those in Smalltalk-80 (not surprising since Objective-C borrows a lot from Smalltalk). Like Smalltalk, in Objective-C, the instance variables and methods are defined by an object's class. A class is an object, hence it is an instance of a metaclass.

Like Smalltalk, in Objective-C, class methods are simply methods called on the class object, hence a class's class methods must be defined as instance methods in its metaclass. Because different classes can have different sets of class methods, each class must have its own separate metaclass. Classes and metaclasses are always created as a pair (the runtime has functions objc_allocateClassPair and objc_registerClassPair to create and register class-metaclass pairs, respectively).

There are no names for the metaclasses; however, a pointer to any class object can be referred to with the generic type Class (similar to the type id being used for a pointer to any object).

Because class methods are inherited through inheritance, like Smalltalk, metaclasses must follow an inheritance scheme paralleling that of classes (e.g. if class A's parent class is class B, then A's metaclass's parent class is B's metaclass), except that of the root class.

Unlike Smalltalk, the metaclass of the root class inherits from the root class itself. (The root class is usually NSObject in Cocoa.) This ensures that all class objects are ultimately instances of the root class, so that you can use the instance methods of the root class (usually useful utility methods for objects) on class objects themselves.

Since metaclass objects do not behave differently (you cannot add class methods for a metaclass, so metaclass objects all have the same methods), they are all instances of the same class—the metaclass of the root class (unlike Smalltalk). (Thus, the metaclass of the root class is an instance of itself.) The reason for this is that all metaclasses inherit from root class; hence, they must inherit the class methods of the root class.

Read more about this topic:  Metaclass