zoukankan      html  css  js  c++  java
  • 懒加载中进行字典转模型

    假设有一个flags.plist文件

    ZWFlags.h

     1 #import <Foundation/Foundation.h>
     2 @interface ZWFlags : NSObject
     3 /** 国旗名字 */
     4 @property (strong, nonatomic)NSString *name;
     5 
     6 /** 国旗图片 */
     7 @property (strong, nonatomic)NSString *icon;
     8 
     9 + (instancetype)flagsWithDict:(NSDictionary *)dict;
    10 
    11 @end

    ZWFlags.m

    #import "ZWFlags.h"
    @interface ZWFlags()
    @end
    @implementation ZWFlags
    
    + (instancetype)flagsWithDict:(NSDictionary *)dict
    {
        ZWFlags *flags = [[self alloc] init];   //此处的self不能用ZWFlags
        flags.name = dict[@"name"];
        flags.icon = dict[@"icon"];  //此处两句也可以直接写成[flags setValuesForKeysWithDictionary:dict]; 
        return flags;
    }
    @end

    在需要使用的控制器中

     1 #import "ViewController.h"
     2 #import "ZWFlags.h"
     3 /** 所有国旗的数据 */
     4 @property (strong, nonatomic)NSMutableArray *flags;
     5 
     6 @end
     7 
     8 @implementation ViewController
     9 
    10 - (NSMutableArray *)flags
    11 {
    12     if (_flags == nil) {
    13         //装flag模型
    14         _flags =[NSMutableArray array];
    15 //        加载plist数据
    16         NSString *path = [[NSBundle mainBundle] pathForResource:@"flags.plist" ofType:nil];
    17         NSArray *arr = [NSArray arrayWithContentsOfFile:path];
    18 //        字典转模型
    19         for (NSDictionary *dict in arr) {
    20             ZWFlags *flag = [ZWFlags flagsWithDict:dict];
    21             [_flags addObject:flag];
    22         }
    23     }
    24     return _flags;
    25 }

    经常看到下面一种,不过上面的简单一些

     1 #import "ViewController.h"
     2 #import "ZWFlags.h"
     3 /** 所有国旗的数据 */
     4 @property (strong, nonatomic)NSArray *flags;
     5 
     6 @end
     7 @implementation ViewController
     8 
     9 - (NSArray *)flags
    10 { 
    11     if (_flags == nil) {
    12         //加载plist文件
    13         NSString *path = [[NSBundle mainBundle] pathForResource:@"flags.plist" ofType:nil];
    14         NSArray *dictArr = [NSArray arrayWithContentsOfFile:path];
    15         
    16         //字典转模型
    17         NSMutableArray *flagArray = [NSMutableArray array];
    18         for (NSDictionary *dict in dictArr) {
    19             ZWFlags *flag = [ZWFlags flagsWithDict:dict];
    20             [flagArray addObject:flag];
    21         }
    22         _flags = flagArray;
    23     }
    24     return _flags;
    25 }
  • 相关阅读:
    HTTP协议【详解】——经典面试题
    原生JS的地区二级联动,很好理解的逻辑
    js操作字符串的常用方法
    移除input框type="number"在部分浏览器的默认上下按钮
    atom
    解决gitHub下载速度慢的问题
    ATOM常用插件推荐
    脚踝扭伤肿了怎么办
    这才是真正的电子科大
    月入 7000,怎么存钱?
  • 原文地址:https://www.cnblogs.com/hissia/p/5432523.html
Copyright © 2011-2022 走看看