Class structure analysis
Isa pointing
So we have an object LGPerson that inherits NSObject and let’s print out isa
// NSObject instance object
LGPerson *object1 = [LGPerson alloc];
/ / NSObject class
Class class = object_getClass(object1);
/ / NSObject metaclass
Class metaClass = object_getClass(class);
// NSObject root metaclass
Class rootMetaClass = object_getClass(metaClass);
// NSObject Root metaclass
Class rootRootMetaClass = object_getClass(rootMetaClass);
NSLog(@"\n%p instance object \n%p class \n%p metaclass \n%p root metaclass \n%p root metaclass",object1,class.metaClass.rootMetaClass.rootRootMetaClass);
Copy the code
Where isa is directed: instance object -> class -> metaclass -> root metaclass -> root metaclass
As shown below
If 0x100008240 is a metaclass, open MacOView and search symbloTable for class 0x100008240
Metaclasses are generated automatically at compile time and are not made available for external use.
Inheritance relationships
Let’s look at inheritance:
Class inheritance:
/ / LGPerson metaclass
Class pMetaClass = object_getClass(LGPerson.class);
Class psuperClass = class_getSuperclass(pMetaClass);
NSLog(@"% @ - % @",pMetaClass,psuperClass);
LGPerson - NSObject
Copy the code
Inheritance of metaclasses
Metaclasses are classes, metaclasses have inheritance, so let’s write a LGTeacher that inherits from a LGPerson
@interface LGTeacher : LGPerson
@end
Copy the code
Class tMetaClass = object_getClass(LGTeacher.class);
Class tsuperClass = class_getSuperclass(tMetaClass);
Class tsuperClass01 = class_getSuperclass(tsuperClass);
Class tsuperClass00 = class_getSuperclass(tsuperClass01);
Class tsuperClass000 = class_getSuperclass(tsuperClass00);
NSLog(@"\ n % @ % p metaclass \ n % @ - father metaclass \ n % p % @ - $% p root class \ % n % @ - p root metaclass super \ % n % @ - p",tMetaClass, tMetaClass, tsuperClass,tsuperClass, tsuperClass01,tsuperClass01, tsuperClass00, tsuperClass00, tsuperClass000,tsuperClass000);
Copy the code
The results are as followsAs you can see from the print, the parent of the root metaclass is NSObject, and Superclass(NULL)–0x0 validates the root class special case
// NSObject root class special case
Class nsuperClass = class_getSuperclass(NSObject.class);
NSLog(@"%@ - %p",nsuperClass,nsuperClass);
(null)--0x0
Copy the code
// Root metaclass -> NSObject
Class rnsuperClass = class_getSuperclass(tsuperClass01);
NSLog(@"%@ - %p",rnsuperClass,rnsuperClass);
NSObject - 0x7fff808b0388
Copy the code
The inheritance diagram is as follows:
The overall process is as follows: