反射机制可以获取的内容
1.获取一个 类的所有属性
1 #pragma -mark 获取变量列表 2 3 -(void)getVarName 4 { 5 unsigned int numIvars; //成员变量个数 6 Ivar *vars = class_copyIvarList(NSClassFromString(@"TestObject"), &numIvars); 7 //Ivar *vars = class_copyIvarList([UIView class], &numIvars); 8 9 NSString *key=nil; 10 for(int i = 0; i < numIvars; i++) { 11 12 Ivar thisIvar = vars[i]; 13 key = [NSString stringWithUTF8String:ivar_getName(thisIvar)]; //获取成员变量的名字 14 NSLog(@"variable name :%@", key); 15 key = [NSString stringWithUTF8String:ivar_getTypeEncoding(thisIvar)]; //获取成员变量的数据类型 16 NSLog(@"variable type :%@", key); 17 } 18 free(vars); 19 20 }
2.获取一个类的所有方法:
1 #pragma -mark 获取方法列表 2 3 -(void)getFunName 4 { 5 unsigned int numIvars; //成员方法个数 6 Method *meth = class_copyMethodList(NSClassFromString(@"TestObject"), &numIvars); 7 //Method *meth = class_copyMethodList([UIView class], &numIvars); 8 9 for(int i = 0; i < numIvars; i++) { 10 Method thisIvar = meth[i]; 11 12 SEL sel = method_getName(thisIvar); 13 const char *name = sel_getName(sel); 14 15 NSLog(@"zp method :%s", name); 16 17 18 } 19 free(meth); 20 }
3.获取变量名
1 #pragma -mark 根据变量属性值获取属性名 2 3 - (NSString *)nameWithInstance:(id)instance 4 { 5 unsigned int numIvars = 0; 6 NSString *key=nil; 7 Ivar * ivars = class_copyIvarList([TestObject class], &numIvars); 8 for(int i = 0; i < numIvars; i++) { 9 Ivar thisIvar = ivars[i]; 10 const char *type = ivar_getTypeEncoding(thisIvar); 11 NSString *stringType = [NSString stringWithCString:type encoding:NSUTF8StringEncoding]; 12 if (![stringType hasPrefix:@"@"]) { 13 continue; 14 } 15 if ((object_getIvar(tObject, thisIvar) == instance)) { 16 key = [NSString stringWithUTF8String:ivar_getName(thisIvar)]; 17 break; 18 } 19 } 20 free(ivars); 21 22 NSLog(@"key:%@",key); 23 24 return key; 25 26 }