zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    c#子类序列化与父类序列化(Serializable)的区别
    eclipse中启动项目报内存溢出问题通过修改配置解决
    java 代码的良好习惯
    s:iterator 标签使用错误记录
    html5 required属性的注意事项
    赋值文件夹名称为日期的doc命令
    cmd命令中截取日期字符
    s:if 标签 字符串比较 正确用法和错误用法
    Resource interpreted as Stylesheet but transferred with MIME type text/plain
    xmind指定32位jdk解决在64位系统上不能启动的问题
  • 原文地址:https://www.cnblogs.com/guchengfengyun/p/4065489.html
Copyright © 2011-2022 走看看