首页 > 代码库 > ios开发 Reflection(二)
ios开发 Reflection(二)
反射机制可以获取的内容
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 }
ios开发 Reflection(二)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。