看到网上有教程关于追踪一个Class的metaClass的方法,楼主使用了objc_getClass(const char*),而正常应该使用object_getClass(Class)。
//实例方法
- (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类",class_isMetaClass(metaClass) ?@"是":@"不是");