Object-C反射讀取實體屬性和值

舉例:atom

首先定義TestModel以下:spa

@interface TestModel : NSObjectip

@property (nonatomic, strong) NSString *name;get

@property (nonatomic, strong) NSString *desc;string

@property (nonatomic, assign) int age;it

@endclass

而後在viewControl中viewDidLoad中添加以下代碼coding

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

    model.name = @"Jack";model

    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

歡迎光臨~~

相關文章
相關標籤/搜索