美文网首页
IOS字典转模型

IOS字典转模型

作者: 程序员大亨 | 来源:发表于2020-11-12 16:52 被阅读0次
    1.定义字典和方法
    @interface ZooModel : NSObject
    @property(nonatomic, copy) NSString *title;
    @property(nonatomic, copy) NSString *answer;
    @property(nonatomic, copy) NSString *icon;
    @property(nonatomic, strong) NSArray *options;
    
    - (instancetype)initWithDict:(NSDictionary *)dictionary;
    
    + (instancetype)zooWithDict:(NSDictionary *)dictionary;
    @end
    
    2.实现转模型方法
    @implementation ZooModel
    - (instancetype)initWithDict:(NSDictionary *)dictionary {
        if (self = [super init]) {
            self.icon = dictionary[@"icon"];
            self.answer = dictionary[@"answer"];
            self.title = dictionary[@"title"];
            self.options = dictionary[@"options"];
        }
        return self;
    }
    
    + (instancetype)zooWithDict:(NSDictionary *)dictionary {
        return [[self alloc] initWithDict:dictionary];
    }
    @end
    
    3.声明常量
    @property(nonatomic, strong) NSArray *db;
    
    4.懒加载plist文件赋值给常量
     (NSArray *)db {
        if (_db == nil) {
            NSString *string = [[NSBundle mainBundle] pathForResource:@"DB" ofType:@"plist"];
            NSArray *array = [NSArray arrayWithContentsOfFile:string];
            NSMutableArray *mutableArray = [NSMutableArray array];
            for (NSDictionary *dictionary in  array) {
                [mutableArray addObject:[[ZooModel alloc] initWithDict:dictionary]];
            }
            _db = mutableArray;
        }
        return _db;
    }
    

    相关文章

      网友评论

          本文标题:IOS字典转模型

          本文链接:https://www.haomeiwen.com/subject/aiypbktx.html