ios中字典转模型的创建以及简单用法

//  appModel.h
// Created by zzqqrr on 17/8/19.
//
#import <Foundation/Foundation.h> @interface appModel : NSObject
@property (nonatomic,copy) NSString *title;
@property (nonatomic,copy) NSString *icon;
- (id)initWithDict:(NSDictionary *)dict;
/**类方法用+号*/
+ (id)appWithDict:(NSDictionary *)dict;
@end //
// appModel.m
// Created by zzqqrr on 17/8/19.
//
#import "appModel.h"

@implementation appModel
//- (id)initWithDict:(NSDictionary *)dict ios7以前不推荐用id
- (instancetype)initWithDict:(NSDictionary *)dict
{
if(self==[super init])
{
self.title=dict[@"title"];
self.icon=dict[@"icon"];
}
return self;
}
//- (id)appWithDict:(NSDictionary *)dict ios7以前不推荐用id
//直接以类名方式调用,不用alloc 规范标准推荐加上
+(instancetype)appWithDict:(NSDictionary *)dict
{
//return [[appModel alloc] initWithDict:dict];
return [[self alloc] initWithDict:dict];
}
@end

//懒加载应用数据
- (NSArray *)apps
{
if(_apps==nil)
{
//获得plist文件全路径
NSString *path=[[NSBundle mainBundle] pathForResource:@"main.plist" ofType:nil];
//加载数组
//_apps=[NSArray arrayWithContentsOfFile:path];
NSArray *dictArray=[NSArray arrayWithContentsOfFile:path];
NSMutableArray *appArray=[NSMutableArray array];
//把字典数组转换成模型对象,放到数组中
for (NSDictionary *dict in dictArray) {
appModel *apps=[[appModel alloc] initWithDict:dict];
appModel *test=[appModel appWithDict:dict];//类名方式调用,同上//把对象添加到数组上
[appArray addObject:apps];
}
_apps=appArray;
}
return _apps;
}
@interface ViewController ()
@property (nonatomic,strong) NSArray *apps;
@end NSDictionary *dict=self.apps[index];//字典
appModel *model=self.apps[index];//模型
上一篇:console打印数组object具体内容


下一篇:js中的call和apply