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 }
  • 相关阅读:
    通过网格拆分高德地图
    vue-router重定向 不刷新问题
    vue-scroller记录滚动位置
    鼠标滚轮更改transform的值(vue-scroller在PC端的上下滑动)
    position sticky的兼容
    js截图及绕过服务器图片保存至本地(html2canvas)
    禁止页面回退到某个页面(如避免登录成功的用户返回到登录页)
    手动创建script解决跨域问题(jsonp从入门到放弃)
    逻辑回归的常见面试点总结
    听说你不会调参?TextCNN的优化经验Tricks汇总
  • 原文地址:https://www.cnblogs.com/hissia/p/5432523.html
Copyright © 2011-2022 走看看