plist文件字典转模型

1.首先定义一个成员变量,存放所需的数据. 即:NSArray *apps

#pragma mark - 重写apps的getter方法
-(NSArray *)apps{
    if (_apps == nil) {
        //加载plist文件
        NSString *path = [[NSBundle mainBundle]pathForResource:@"app.plist" ofType:nil];
        //plist文件里的字典存放在一个数组当中
        NSArray *dictArray = [[NSArray alloc]initWithContentsOfFile:path];
        //创建一个可变数组用来存放模型数据(字典转的模型)
        NSMutableArray *appArray = [NSMutableArray array];
        //遍历数组(plist文件中数组存放的都是字典对象随意使用NSDictionary *dict)
        //下面需要创建模型(就是一个用来存放数据的类).
        for (NSDictionary *dict in dictArray) {
            //这里使用了一个小方法:需求驱动方法(本身AppModel中没有initWithDict构造方法)
            AppModel *app = [[AppModel alloc]initWithDict:dict];
            //将所有的AppModel模型都放在前面定义的NSMutableArray *appArray数组中
            [appArray addObject:app];
        }
        //将可变可变数组appArray中的模型数据赋值给成员变量_apps数组
        _apps = appArray;
    }
    return _apps;
}

2. 创建数据模型(上文中的 AppModel类)

//下面是模型类的.h文件
#import <Foundation/Foundation.h>

@interface AppModel : NSObject
//类中声明两个属性与字典中的key一样
@property (nonatomic,copy) NSString *icon;
@property (nonatomic,copy) NSString *name;

//定义一个构造方法和一个快速创建对象的类方法
-(instancetype)initWithDict:(NSDictionary *)dict;
+(instancetype)modelWithDict:(NSDictionary *)dict;

@end
//下面是模型类.m文件
#import "AppModel.h"

@implementation AppModel
//重写构造方法 此方法是固定的
-(instancetype)initWithDict:(NSDictionary *)dict{
    
    if (self = [super init]) {
        self.name = dict[@"name"];
        self.icon = dict[@"icon"];
    }
    return self;
}
//提供一个类时,最好提供一个类方法(即静态方法),调用构造方法快速创建类对象
+(instancetype)modelWithDict:(NSDictionary *)dict{
    return [[self alloc]initWithDict:dict];
}
@end

 

posted @ 2014-11-18 01:26  高了个辉  阅读(207)  评论(0编辑  收藏  举报