博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Object-C反射读取实体属性和值

Posted on 2014-02-27 18:47  吕霖  阅读(726)  评论(0编辑  收藏  举报

举例:

首先定义TestModel如下:

@interface TestModel : NSObject

@property (nonatomic, strong) NSString *name;

@property (nonatomic, strong) NSString *desc;

@property (nonatomic, assign) int age;

@end

然后在viewControl中viewDidLoad中添加如下代码

    TestModel *model = [[TestModel alloc] init];

    model.name = @"Jack";

    model.age = 30;

    model.desc = @"some thing right";

    

    unsigned int outCount, i;

    objc_property_t *properties = class_copyPropertyList([model class], &outCount);

    

    for (i=0; i<outCount; i++) {

        objc_property_t property = properties[i];

        

        const char *propertyName =  property_getName(property);

        const char *propertyAttribute =  property_getAttributes(property);

        

        NSString  *name=[NSString  stringWithCString:propertyName

                                            encoding:NSUTF8StringEncoding];

        

        NSString  *attribute=[NSString  stringWithCString:propertyAttribute

                                                 encoding:NSUTF8StringEncoding];

        

        

        id value = [model valueForKey:[NSString stringWithUTF8String:propertyName]];

        NSString * key = [[NSStringalloc]initWithCString:property_getName(property) encoding:NSUTF8StringEncoding];

        

        NSLog(@"%@==%@\n",name,attribute);

        NSLog(@"property[%d]:%@  value:%@\n", i, key, value);

    }

 

执行结果如下:

2014-03-01 05:35:38.560 snippet[7267:70b] name==T@"NSString",&,N,V_name

2014-03-01 05:35:38.562 snippet[7267:70b] property[0]:name  value:Jack

2014-03-01 05:35:38.562 snippet[7267:70b] desc==T@"NSString",&,N,V_desc

2014-03-01 05:35:38.563 snippet[7267:70b] property[1]:desc  value:some thing right

2014-03-01 05:35:38.563 snippet[7267:70b] age==Ti,N,V_age

2014-03-01 05:35:38.564 snippet[7267:70b] property[2]:age  value:30

欢迎光临~~