看到網(wǎng)上有教程關(guān)于追蹤一個(gè)Class的metaClass的方法纫事,樓主使用了objc_getClass(const char*)切平,而正常應(yīng)該使用object_getClass(Class)。
//實(shí)例方法
- (void)generateClassTest
{
Class newClass =objc_allocateClassPair([NSErrorclass],"TestClass",0);
class_addMethod(newClass,@selector(testMetaClass), (IMP)(testMetaClassImp),"v@:");
objc_registerClassPair(newClass);
idinstance = [[newClassalloc]initWithDomain:@"dynamic generate class" code:0 userInfo:nil];
[instanceperformSelector:@selector(testMetaClass)];
}
//c接口
void testMetaClassImp(id self,SEL cmd)
{
NSLog(@"this Object is %p\n\n",self);
NSLog(@"class is %@, super class is %@\n\n",[selfclass], [selfsuperclass]);
Class currentClass = [selfclass];
for(inti =0; i <4; i ++) {
NSLog(@"Following the isa pointer %d times gives %p\n\n", i, currentClass);
//currentClass = objc_getClass((__bridge void*)currentClass); // --wrong
currentClass =object_getClass(currentClass);// --right
}
NSLog(@"NSObject's class is %p\n\n",[NSObjectclass]);
//NSLog(@"NSObject's meta class is %p\n\n",objc_getClass((__bridge void*)[NSObject class])); // --wrong
NSLog(@"NSObject's meta class is %p\n\n",object_getClass([NSObjectclass]));// --right
Class metaClass =object_getClass([NSObjectclass]);// --right
//metaClass = objc_getClass((__bridge void*)[NSObject class]);// --wrong
NSLog(@"object_getClass([NSObject class])返回的%@ NSObject的meta類(lèi)",class_isMetaClass(metaClass) ?@"是":@"不是");