字典转模型

1.懒加载

// 加载plist数据(比较大)
// 懒加载:用到时再去加载,而且也只加载一次
- (NSArray *)shops
{
    if (_shops == nil) {
        // 加载一个字典数组
        NSArray *dictArray = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"shops" ofType:@"plist"]];
        
        NSMutableArray *shopArray = [NSMutableArray array];
        for (NSDictionary *dict in dictArray) {
            XMGShop *shop = [XMGShop shopWithDict:dict];
            [shopArray addObject:shop];
        }
        _shops = shopArray;
    }
    return _shops;
}

2.模型类
(1).h文件

#import 

@interface XMGShop : NSObject
/** 商品名称 */
@property (nonatomic, strong) NSString *name;
/** 图标 */
@property (nonatomic, strong) NSString *icon;

- (instancetype)initWithDict:(NSDictionary *)dict;
+ (instancetype)shopWithDict:(NSDictionary *)dict;
@end

(2).m文件

#import "XMGShop.h"

@implementation XMGShop
- (instancetype)initWithDict:(NSDictionary *)dict
{
    if (self = [super init]) {
        self.name = dict[@"name"];
        self.icon = dict[@"icon"];
    }
    return self;
}

+ (instancetype)shopWithDict:(NSDictionary *)dict
{
    return [[self alloc] initWithDict:dict];
}
@end

你可能感兴趣的:(字典转模型)