isa指標的實現是相當於呼叫方法:object_getClass(id )
[object class]的實現相當於呼叫方法:objc_getClass(const char * _Nonnull name)
這兩個方法的區別可以通過下面兩個例子來展示:
Son *sonObject = [Son new];
Class currentClass = [sonObject class];
const char *className = object_getClassName(currentClass);
/*
sonObject->(class)Son->(isa)MetaClassOfSon->(isa)MetaClassOfNSObject->(isa)MetaClassOfNSObject
*/
for (int i=0; i<4; i++) {
NSLog(@"class:%p-----className:%s-------superClass:%@\n",currentClass,className,[currentClass superclass]);
currentClass = object_getClass(currentClass);
className = object_getClassName(currentClass);
}
複製程式碼
列印結果:
從中可以看到最後兩次列印的currentClass地址相同,說明最後MetaClassOfNSObject的isa指標最終指向了本身。
Son *sonObject = [Son new];
Class currentClass = [sonObject class];
const char *className = object_getClassName(currentClass);
for (int i=0; i<4; i++) {
NSLog(@"class:%p-----className:%s-------superClass:%@\n",currentClass,className,[currentClass superclass]);
currentClass = objc_getClass([NSStringFromClass(currentClass) UTF8String]);
className = object_getClassName(currentClass);
}
複製程式碼
列印結果:
由此可知objc_getClass方法只是單純地返回了Class,而非isa指標指向的Class