object\Classes and metaclasses

typedef struct objc_object {
    Class isa;
} *id;


typedef struct objc_class *Class;
struct objc_class {
    Class isa;
    Class super_class;
    /* followed by runtime specific details... */
};

Objective-C is a class-based object system. Each object is an instance of some class; the object's isa pointer points to its class. That class describes the object's data: allocation size and ivar types and layout. The class also describes the object's behavior: the selectors it responds to and instance methods it implements.

Each Objective-C class is also an object. It has an isa pointer and other data, and can respond to selectors. When you call a "class method" like [NSObject alloc], you are actually sending a message to that class object. 


Since a class is an object, it must be an instance of some other class: a metaclass. The metaclass is the description of the class object, just like the class is the description of ordinary instances.

 

What is needed for a data structure to be an object?

Every object has a class. This is a fundamental object-oriented concept but in Objective-C, it is also a fundamental part of the data. Any data structure which has a pointer to a class in the right location can be treated as an object.

In Objective-C, an object's class is determined by its isa pointer. The isa pointer points to the object's Class.

In fact, the basic definition of an object in Objective-C looks like this:

typedef struct objc_object {
    Class isa;
} *id;

What this says is: any structure which starts with a pointer to a Class structure can be treated as an objc_object.

The most important feature of objects in Objective-C is that you can send messages to them:

 

What is a meta-class?

This leads to the definition of a meta-class: the meta-class is the class for a Class object.

Simply put:

  • When you send a message to an object, that message is looked up in the method list on the object's class.
  • When you send a message to a class, that message is looked up in the method list on the class' meta-class.

The meta-class is essential because it stores the class methods for a Class. There must be a unique meta-class for every Class because every Class has a potentially unique list of class methods.

 

https://www.cocoawithlove.com/2010/01/what-is-meta-class-in-objective-c.html

http://www.sealiesoftware.com/blog/archive/2009/04/14/objc_explain_Classes_and_metaclasses.html

posted @ 2021-08-04 23:52  zzfx  阅读(40)  评论(0编辑  收藏  举报