黑马程序员技术交流社区

标题: 今天自学了字典转模型,总结一下大致有下面几个步骤,望大神们指教指教 [打印本页]

作者: 1158865593    时间: 2015-7-25 00:15
标题: 今天自学了字典转模型,总结一下大致有下面几个步骤,望大神们指教指教
字典转模型(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




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2