這里簡單介紹如何使用runtime將JSON轉(zhuǎn)換成Model.
封裝initWithNSDictionary:方法
該方法接收NSDictionary對(duì)象, 返回PersonModel對(duì)象.
#pragma mark - 使用runtime將JSON轉(zhuǎn)成Model
- (void)json2Model {
NSString *file = [[NSBundle mainBundle] pathForResource:@"Persons" ofType:@"json"];
NSData *data = [NSData dataWithContentsOfFile:file];
NSMutableArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
for (NSDictionary *model in array) {
PersonModel *person = [[PersonModel alloc] initWithNSDictionary:model];
NSLog(@"%@, %ld, %@, %@", person.name, (long)person.age, person.city, person.job);
}
}
使用runtime實(shí)現(xiàn)
PersonModel的頭文件如下:
#import <Foundation/Foundation.h>
@interface PersonModel : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) NSInteger age;
@property (nonatomic, copy) NSString *city;
@property (nonatomic, copy) NSString *job;
- (instancetype)initWithNSDictionary:(NSDictionary *)dict;
@end
實(shí)現(xiàn)文件:
#import "PersonModel.h"
#import <objc/runtime.h>
@implementation PersonModel
- (instancetype)initWithNSDictionary:(NSDictionary *)dict {
self = [super init];
if (self) {
[self prepareModel:dict];
}
return self;
}
- (void)prepareModel:(NSDictionary *)dict {
NSMutableArray *keys = [[NSMutableArray alloc] init];
u_int count = 0;
objc_property_t *properties = class_copyPropertyList([self class], &count);
for (int i = 0; i < count; i++) {
objc_property_t property = properties[i];
const char *propertyCString = property_getName(property);
NSString *propertyName = [NSString stringWithCString:propertyCString encoding:NSUTF8StringEncoding];
[keys addObject:propertyName];
}
free(properties);
for (NSString *key in keys) {
if ([dict valueForKey:key]) {
[self setValue:[dict valueForKey:key] forKey:key];
}
}
}
@end
其中的代碼也很簡單:
使用class_copyPropertyList獲取Model的所有屬性列表, 遍歷該列表使用property_getName即可得到所有屬性名.
對(duì)于PersonModel中定義的屬性, 使用KVC即可將dict中的值賦給該屬性.
Demo
Demo請參考:
iOS-RuntimeDemo.