Runtime的使用——利用Runtime將字典轉成Model

關於runtime的知識已經有不少的講解(傳送門:對runtime的理解 http://www.jianshu.com/p/927c8384855a),但一直不知道runtime的使用場景, 接下來利用runtime實現將字典轉換成model。但願你們對runtime的使用有個初步瞭解。測試

首先定義個RuntimeModel 類atom

//RuntimeModel.h
#import <Foundation/Foundation.h>
#import <objc/runtime.h>   //別忘記引入庫
@interface RuntimeModel : NSObject

-(instancetype)initWithDic :(NSDictionary *)dic;

@end


//RuntimeModel.m
-(instancetype)initWithDic :(NSDictionary *)dic {
    self = [super init];
    if (self) {
        NSMutableArray * keyArray = [NSMutableArray array];
        NSMutableArray * attributeArray = [NSMutableArray array];
        unsigned  int outCount = 0 ;
        objc_property_t * propertys = class_copyPropertyList([self  class], &outCount); //獲取該類的屬性列表
        for (int i = 0 ; i < outCount; i++) {
            objc_property_t    property =  propertys[i];
            NSString * propertyName = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding]; //獲取屬性對應的名稱
            [keyArray addObject:propertyName];   
        }
        free(propertys); //記得要釋放
        for (NSString * key in keys) {
            
            if (![keyArray containsObject:key]||[dic valueForKey:key] == nil) continue ;
            [self setValue:[dic valueForKey:key] forKey:key];
        }
    }
    return self;
}

而後咱們建立個model繼承RuntimeModel類,並添加屬性spa

//  DataModel.h
#import <Foundation/Foundation.h>
#import "RuntimeModel.h"
@interface DataModel : RuntimeModel
@property (nonatomic , strong)NSString *  name ;
@property (nonatomic , strong)NSString *  imageUrl;

接下來能夠在ViewController裏調用試試結果code

- (void)viewDidLoad {
    [super viewDidLoad];
     NSDictionary * dic = [[NSDictionary alloc]initWithObjectsAndKeys:@"測試",@"name",@"圖片連接",@"imageUrl", nil];
    DataModel * model = [[DataModel alloc]initWithDic:dic];
    NSLog(@"name --%@ , imageUrl --%@",model.name ,model.imageUrl);
   }

 測試結果是繼承

  2016-03-25 11:21:49.626 Wheat[750:64557] name --測試 , imageUrl --圖片連接圖片

相關文章
相關標籤/搜索