字典转模型的例子

来源:互联网 发布:vocaloid软件 编辑:程序博客网 时间:2024/06/06 03:04

  在前两篇中,我们用到了字典,现在想将字典转为模型

1.使用字典的坏处
    一般情况下,设置数据和取出数据都使用“字符串类型的key”,编写这些key时,编译器不会有任何友善提示,需要手敲 ,如
   
dict[@"name"] = @"天天跑酷";  NSString*name = dict[@"name"];

    手敲字符串key,key容易写错
    Key如果写错了,编译器不会有任何警告和报错,造成设错数据或者取错数据

2.使用模型的好处
     所谓模型,其实就是数据模型,专门用来存放数据的对象,用它来表示数据会更加专业
     模型设置数据和取出数据都是通过它的属性,属性名如果写错了,编译器会马上报错,因此,保证了数据的正确性
     使用模型访问属性时,编译器会提供一系列的提示,提高编码效率

app.name = @"天天跑酷”;NSString*name = app.name;



3.字典转模型的过程最好封装在模型内部
    
模型应该提供一个可以传入字典参数的构造方法- (instancetype)initWithDict:(NSDictionary *)dict;+ (instancetype)xxxWithDict:(NSDictionary *)dict;

4.下面就前面的那个例子说明一下怎么将字典转为模型,并使用它
   4.1:创建模型的文件
       New File -> Source->Cocoa Touch Class -> 
 里面的Subclass of 选择NSObject

   4.2
  在app.h中
@interface app : NSObject//名称@property(nonatomic,copy) NSString *name;//图像@property(nonatomic,copy) NSString *icon;//通过字典来初始化模型对象 dict 为字典对象,return 已经初始化完毕的模型对象-(instancetype)initWithDict:(NSDictionary *)dict;+(instancetype)appWithDict:(NSDictionary *)dict;@end

 app.m中
@implementation app-(instancetype)initWithDict:(NSDictionary *)dict{        if (self = [super init]) {        self.name = dict[@"name"];        self.icon = dict[@"icon"];    }   return self;}+(instancetype)appWithDict:(NSDictionary *)dict{    return [[self alloc]initWithDict:dict];}@end

 4.3
在ViewController.m中,修改

-(NSArray *)apps


//plist-(NSArray *)apps{    if (_apps == nil) {        //初始化                //1.获得plist的全路径                NSBundle *bundle = [NSBundle mainBundle];        NSString *plistPath = [bundle pathForResource:@"app.plist" ofType:nil];                //2.加载数组        NSArray *dictArray = [NSArray arrayWithContentsOfFile:plistPath];                //3.将dictArray里面的所有字典转成模型对象,放到新的数组中        NSMutableArray *appArray = [NSMutableArray array];        for (NSDictionary *dict in dictArray) {            //创建模型对象            //app *app1 = [[app alloc]initWithDict:dict];            app *app1 = [app appWithDict:dict];                        //添加模型对象到数组中            [appArray addObject:app1];        }        //4.赋值        _apps = appArray;            }    return _apps;}

4.4

这样就可以在程序中使用模型啦

for循环里面的

      /**  将三个组件添加到小框框中*/          //0.index位置对应的应用信息        NSDictionary *appInfo = self.apps[index];        
改为

     /**  将三个组件添加到小框框中*/          //0.index位置对应的应用信息        app *appInfo = self.apps[index];

            //设置图片        image.image = [UIImage imageNamed:appInfo[@"icon"]];

          //设置图像名的文字        name.text = appInfo[@"name"];

改为

             //设置图片        image.image = [UIImage imageNamed:appInfo.icon];

         //设置图像名的文字        name.text = appInfo.name;

这样就行了



0 0