设为首页 加入收藏

TOP

懒加载中进行字典转模型
2017-10-13 10:24:26 】 浏览:1073
Tags:加载 进行 字典 模型

假设有一个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 }

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇关于nsurlsession 下一篇iOS dom解析xml格式数据

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目