objc_getClass参数是类名的字符串,返回的就是这个类的类对象;object_getClass参数是id类型,它返回的是这个id的isa指针所指向的Class,如果传参是Class,则返回该Class的metaClass。
Class currentClass = [self class];
const char *a = object_getClassName(currentClass);
for (int i = 1; i < 5; i++) {
NSLog(@"Following the isa pointer %d times gives %p---%s", i, currentClass,a);
currentClass = object_getClass(currentClass);
a = object_getClassName(currentClass);
}
上面一段代码输出的是:
Following the isa pointer 1 times gives 0x7fe273f0a880—DBTestView
Following the isa pointer 2 times gives 0x7fe273f0a8b0—NSObject
Following the isa pointer 3 times gives 0x100eaa198—NSObject
Following the isa pointer 4 times gives 0x100eaa198—NSObject,
由此我们可以看到,object_getClass返回的其实是class的metaClass,即Class这个类对象的类,这个概念有点绕。梳理一下:DBTestView这么一个类(0x7fe273f0a880),它的isa指针指向其元类(地址0x7fe273f0a8b0),这个元类的isa指针指向基类NSObject的元类,即根元类(0x100eaa198),再递进一层可以发现,根元类的isa指针指向自己,这样就形成了一个完整的闭环。
换一套实现:
Class currentClass = [self class];
const char *a = object_getClassName(currentClass);
for (int i = 1; i < 5; i++) {
NSLog(@"Following the isa pointer %d times gives %p---%s", i, currentClass,a);
currentClass = objc_getClass([NSStringFromClass(currentClass)UTF8String]);
a = object_getClassName(currentClass);
}
输出为:
Following the isa pointer 1 times gives 0x7ff931e239a0—DBTestView
Following the isa pointer 2 times gives 0x7ff931e239a0—DBTestView
Following the isa pointer 3 times gives 0x7ff931e239a0—DBTestView
Following the isa pointer 4 times gives 0x7ff931e239a0—DBTestView
由此可知objc_getClass方法只是单纯地返回了Class,而非isa指针指向的Class。