字典转模型(model)
--1.新建模型类(Model.h/Model.m)
--2在.h文件中声明.plist文件中字典的各个属性(如:name属性---@property(nonatomin,copy)NSString * name;)并声明:
-(instancetype)initWithDict:(NSDictionary *)dict;
+(instancetype) XXXWithDict:(NSDictionary *) dict;
--3.在.m文件中实现方法:
-(instancetype)initWithDict:(NSDictionary *)dict
{
if(self=[super init]){
[self setValuesForKeysWithDictionary:dict];
return self;
}
+ (instancetype)XXXWithDict:(NSDictionary *)dict
{
return [[self alloc] initWithDict:dict];
}
@end
--4在.m文件中导入头文件并声明数组:@property (nonatomic, strong) NSArray *xxxxx;
---5.取出数组:
- (NSArray *)xxxxx
{
if (_xxxxxx == nil) {
// 1.加载plist
NSArray *dictArray = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@“xxxxx" ofType:@"plist"]];
// 2.字典转模型
NSMutableArray *xxxxxArray = [NSMutableArray array];
for (NSDictionary *dict in dictArray) {
Model *xxxxx = [Model xxxxxWithDict:dict];
[xxxxxArray addObject:xxxxx];
}
// 3.赋值
_xxxxxx = xxxxxnArray;
}
return _xxxxxx;
}
:lol |
|