懒加载中进行字典转模型

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

 

posted @ 2016-04-25 20:05  hissia  阅读(328)  评论(0编辑  收藏  举报