栗子:有一个ZHHAssertNewNew类,类中有两个属性
@property (nonatomic, strong) NSString* name;
@property (nonatomic, assign) int age;
1,导入#import <objc/runtime.h>
2,实现方法
void test() {
u_int count = 0;
Ivar* ivars = class_copyIvarList(objc_getClass("ZHHAssertNewNew"), &count);
for (int i=0; i<count; i++) {
Ivar ivar = ivars[i];
//name
const char* name = ivar_getName(ivar);
NSLog(@"name->%s",name);
//type
const char* type = ivar_getTypeEncoding(ivar);
NSLog(@"type->%s",type);
//得到实际的类型
Class c = realTypeWithType(type);
NSLog(@"class->%@",c);
/* log打印结果
name->_age
type->i
class->(null)
name->_name_
type->@"NSString"
class->NSString
*/
/*
关于type
如果返回i代表int类型
如果返回@"NSString"代表NSString
...同理
*/
}
//释放:与copy对应
free(ivars);
}
//通过返回类型返回实际类型
Class realTypeWithType(const char* type) {
NSString* code = [NSString stringWithUTF8String:type];
if ([code hasPrefix:@"@"] && (code.length > 3)) {
//去掉前面的@"和后面的"
code = [code substringFromIndex:2];
code = [code substringToIndex:code.length-1];
return NSClassFromString(code);
}
//基本数据类型没做处理
return nil;
}
3,调用.