zoukankan      html  css  js  c++  java
  • 关于字典转模型的个人理解

    1.字典跟模型的优缺点比较:

    1>字典在使用key的时候Xcode不会有提示,容易出错,模型就不会

    2>①所谓模型,其实就是数据模型,专门用来存放数据的对象,用它来表示数据会更加专业

    ②模型设置数据和取出数据都是通过它的属性,属性名如果写错了,编译器会马上报错,因此,保证了数据的正确性

    ③使用模型访问属性时,编译器会提供一系列的提示,提高编码效率

    2.字典转模型的过程(中间加了一些个人想法)

    1.>首先需要创建一个plist文件,将字典中的元素添加到plist文件中

    注意:应该是创建的NSArray包含NSDictionary,NSDictionary包含NSString

    2.>接下来应该在model文件夹创建新的文件并在.h文件中添加两个方法

    +(instancetype)****WithDict: (NSDictionary*)dict;

    -(instancetype)initWithDict: (NSDictionary*)dict;

    3>在新创建的文件中实现。

    +(instancetype)****WithDict:(NSDictionary*)dict

    {

    return[[selfalloc]initWithDict:dict];

    }

    -(instancetype)initWithDict:(NSDictionary*)dict

    {

    if(self= [superinit]) {

    self.name= dict[@"name"];

    self.icon= dict[@"icon"];

    }

    returnself;

    }

    4>在viewController中添加一个数组属性的变量,然后在将字典转模型(最重要的一步)

    @property(strong,nonatomic)NSArray*shops;

    -(NSArray*)shops

    {

    //初始化数组

    if(_shops==nil) {

    //获取plist的全路径

    NSString*path = [[NSBundlemainBundle]pathForResource:@"shop.plist"ofType:nil];

    //加载数组

    NSArray*dictArray = [NSArrayarrayWithContentsOfFile:path];

    /**

    *将dictArray中所有字典转为模型对象

    */

    NSMutableArray*shopArray = [NSMutableArrayarray];

    /**

    *利用for in遍历数组的字典

    */

    for(NSDictionary*dictindictArray) {

    //创建模型对象

    YHShop*shop = [YHShopshopWithDict:dict];

    //添加模型对象到数组

    [shopArrayaddObject:shop];

    }

    _shops= shopArray;

    }

    return_shops;//这里返回的就是一个包含模型的数组

    }

    @end

    5.将之前在使用数组的地方直接改为模型:例如:

    YHShop*shopInfo =self.shops[index];//把模型数据给一个新的对象

    imageView.image= [UIImageimageNamed:shopInfo.icon];

    ☆比较简单的理解方式:把之前的数组中的字典抽取出来,创建模型对象,然后把这些模型放到一个新的数组中,通过调用这个数组,进而使用其中的模型。

  • 相关阅读:
    SSD5_Optional Exercise 5分析
    SSD5_Optional Exercise 3分析
    SSD5_Optional Exercise 1 分析
    SSD5_Optional Exercise 4不会
    SSD5_ Exercise 2分析
    SSD5_Optional Exercise 2分析
    SSD5_Exercise 3分析
    SSD5_Recommended Exercise 4 分析
    2013蓝桥杯C语言本科组B
    hdu 1316 How Many Fibs?【JAVA大数】
  • 原文地址:https://www.cnblogs.com/kings0secret-cn/p/5191424.html
Copyright © 2011-2022 走看看