iOS class: instance objects, class objects, metaclasses, and isa pointers

Please indicate the source for reprint http://blog.csdn.net/u014205968/article/details/64921601

Each object in object-oriented must rely on a class to create, so the isapointer of the object points to the class to which the object belongs. According to this class template, instance variables, instance methods, etc. can be created. 

For example, the following code

NSString* str = @"Hello World";

From the above, we know that this strobject is essentially a objc_objectstructure, and the member variable isapointer of this structure indicates that str is a NSString, so this isapoints to a NSStringclass. This NSStringclass is actually a class object. If you don't understand, continue to read it.


class object/metaclass

objc_classContinue to view the definition of the structure

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 *` */

struct objc_classsThe data stored in the structure is called 元数据(metadata). Through the name of the member variable, we can guess that it stores the pointer to the parent class, the name of the class, the version, the instance size, the list of instance variables, the list of methods, the cache, the list of protocols to be followed, etc., This information is enough to create an instance. The first member variable of the structure is also a isapointer, which means that it Classis actually an object. We call it a singleton, which is generated at compile time to create an instance object 类对象. 类对象Therefore, the chestnut in the previous article should actually be expressed as what does str的isa指针指向了NSString类对象the pointer of this structure isapoint to?

类对象The 元数据information stored in is how to create an instance, so 类对象and 类方法where should it be created? It is isacreated from the structure pointed to by the pointer, and 类对象the isapointer pointed to by us calls it 元类(metaclass), and all the information needed 元类for creation 类对象and creation is stored in it 类方法, so the whole structure should be as shown in the following figure:




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325959421&siteId=291194637