美文网首页
runtime获取类的属性列表和方法列表

runtime获取类的属性列表和方法列表

作者: 海牛骑士 | 来源:发表于2018-04-16 14:01 被阅读26次

    新建一个Animal类  给类添加一些成员变量、属性、和方法。

    在控制器里面使用该类 并 给相应的变量赋值  

      //获取类方法和属性列表

        Animal *mal=[[Animal alloc]init];

        [malsetValue:@"大象" forKey:@"name"];

        [malsetValue:@"陆地" forKey:@"type"];

        [malsetValue:@"grayColor" forKey:@"color"];

        //属性

         mal.tName=@"动物";

         mal.wailt=@60;

    下面 我们就开始用runtime来获取一下该类的一些成员变量 属性 和方法列表 

    //获取 属性 方法  成员 变量  列表

    -(void)runtimeList:(Animal*)animal

    {

        unsigned  int  count;

        //获取属性列表

        objc_property_t  *propertys=class_copyPropertyList([animal class], &count);

        for(NSIntegerindex=0; index

        {

            constchar* propertyName=property_getName(propertys[index]);

            NSString *name=[NSString stringWithUTF8String:propertyName];

            //打印属性和对应的值值

            NSLog(@"%@ -------%@",name,[animal valueForKey:name]);

        }

        free(propertys);

        //获取成员变量列表

        Ivar  *ivars=class_copyIvarList([animalclass], &count);

        for(NSIntegerindex=0; index

            const  char* ivarName=ivar_getName(ivars[index]);

            NSString *name=[NSString  stringWithUTF8String:ivarName];

            //打印成员变量和值

            NSLog(@"%@---------%@",name ,[animal valueForKey:name]);

        }

        free(ivars);

        //获取方法列表

        Method*methedList=class_copyMethodList([animalclass], &count);

        for(NSIntegerindex=0; index

            SEL  methodName=method_getName(methedList[index]);

            constchar* name=sel_getName(methodName);

            NSString *strName=[NSString stringWithUTF8String:name];

            NSLog(@"%@",strName);

        }

        free(methedList);

        //获取协议列表

        __unsafe_unretained  Protocol ** proList= class_copyProtocolList([animal class], &count);

        for(NSIntegerindex=0; index

            Protocol*proName=proList[index];

            constchar*protocolName=protocol_getName(proName);

            NSString *name=[NSString stringWithUTF8String:protocolName];

            NSLog(@"%@",name);

        }

    }

    控制台 打印 

    相关文章

      网友评论

          本文标题:runtime获取类的属性列表和方法列表

          本文链接:https://www.haomeiwen.com/subject/gtiskftx.html