码迷,mamicode.com
首页 > 其他好文 > 详细

反射--> 属性赋值

时间:2018-02-22 16:43:17      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:blog   list   atomic   run   end   arp   body   undle   jin   

 

Persons.json文件

[
 {
 "name": "Chris",
 "age": 18,
 "city": "Shanghai",
 "job": "iOS"
 },
 {
 "name": "Ada",
 "age": 16,
 "city": "Beijing",
 "job": "student"
 },
 {
 "name": "Rita",
 "age": 17,
 "city": "Xiamen",
 "job": "HR"
 }
 ]

 Model.h类

 1 #import <Foundation/Foundation.h>
 2 
 3 @interface PersonModel : NSObject
 4 
 5 @property (nonatomic, copy) NSString *name;
 6 @property (nonatomic, assign) NSInteger age;
 7 @property (nonatomic, copy) NSString *city;
 8 @property (nonatomic, copy) NSString *job;
 9 @property (nonatomic, copy) NSString *sex;
10 
11 - (instancetype)initWithNSDictionary:(NSDictionary *)dict;
12 
13 @end

 

Model.m类

 1 #import "PersonModel.h"
 2 #import <objc/runtime.h>
 3 
 4 @implementation PersonModel
 5 
 6 - (instancetype)initWithNSDictionary:(NSDictionary *)dict {
 7     self = [super init];
 8     if (self) {
 9         [self prepareModel:dict];
10     }
11     return self;
12 }
13 
14 - (void)prepareModel:(NSDictionary *)dict {
15     NSMutableArray *keys = [[NSMutableArray alloc] init];
16     
17     u_int count = 0;
18     objc_property_t *properties = class_copyPropertyList([self class], &count);
19     for (int i = 0; i < count; i++) {
20         objc_property_t property = properties[i];
21         const char *propertyCString = property_getName(property);
22         NSString *propertyName = [NSString stringWithCString:propertyCString encoding:NSUTF8StringEncoding];
23         [keys addObject:propertyName];
24     }
25     free(properties);
26     
27     for (NSString *key in keys) {
28         if ([dict valueForKey:key]) {
29             [self setValue:[dict valueForKey:key] forKey:key];
30         }
31     }
32 }
33 
34 @end

 

 

调用

1 NSString *file = [[NSBundle mainBundle] pathForResource:@"Persons" ofType:@"json"];
2     NSData *data = [NSData dataWithContentsOfFile:file];
3     NSMutableArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
4     
5     for (NSDictionary *model in array) {
6         PersonModel *person = [[PersonModel alloc] initWithNSDictionary:model];
7         NSLog(@"%@, %ld, %@, %@", person.name, (long)person.age, person.city, person.job);
8     }

 

 

打印结果:

技术分享图片

 

反射--> 属性赋值

标签:blog   list   atomic   run   end   arp   body   undle   jin   

原文地址:https://www.cnblogs.com/EchoHG/p/8458337.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!