IOS 字典转模型
2015-10-07 17:15
323 查看
用模型存放字典上的内容,方便使用
一、创建类MJHero
1、在头文件声明属性,声明对象方法,类方法
#import <Foundation/Foundation.h>
@interface MJHero : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *icon;
@property (nonatomic, copy) NSString *intro;
+ (instancetype)heroWithDict:(NSDictionary *)dict;
- (instancetype)initWithDict:(NSDictionary *)dict;
@end
2、在.m实现方法
#import "MJHero.h"
@implementation MJHero
+ (instancetype)heroWithDict:(NSDictionary *)dict
{
return [[self alloc] initWithDict:dict];
}
- (instancetype)initWithDict:(NSDictionary *)dict
{
if (self = [super init]) {
[self setValuesForKeysWithDictionary:dict];
}
return self;
}
@end
二、在ViewController.m中添加数组和get方法
#import "MJViewController.h"
#import "MJHero.h"
@property (nonatomic, strong) NSArray *heros;
- (NSArray *)heros
{
if (_heros == nil) {
// 初始化
// 1.获得plist的全路径
NSString *path = [[NSBundle mainBundle] pathForResource:@"heros.plist" ofType:nil];
// 2.加载数组
NSArray *dictArray = [NSArray arrayWithContentsOfFile:path];
// 3.将dictArray里面的所有字典转成模型对象,放到新的数组中
NSMutableArray *heroArray = [NSMutableArray array];
for (NSDictionary *dict in dictArray) {
// 3.1.创建模型对象
MJHero *hero = [MJHero heroWithDict:dict];
// 3.2.添加模型对象到数组中
[heroArray addObject:hero];
}
// 4.赋值
_heros = heroArray;
}
return _heros;
}
一、创建类MJHero
1、在头文件声明属性,声明对象方法,类方法
#import <Foundation/Foundation.h>
@interface MJHero : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *icon;
@property (nonatomic, copy) NSString *intro;
+ (instancetype)heroWithDict:(NSDictionary *)dict;
- (instancetype)initWithDict:(NSDictionary *)dict;
@end
2、在.m实现方法
#import "MJHero.h"
@implementation MJHero
+ (instancetype)heroWithDict:(NSDictionary *)dict
{
return [[self alloc] initWithDict:dict];
}
- (instancetype)initWithDict:(NSDictionary *)dict
{
if (self = [super init]) {
[self setValuesForKeysWithDictionary:dict];
}
return self;
}
@end
二、在ViewController.m中添加数组和get方法
#import "MJViewController.h"
#import "MJHero.h"
@property (nonatomic, strong) NSArray *heros;
- (NSArray *)heros
{
if (_heros == nil) {
// 初始化
// 1.获得plist的全路径
NSString *path = [[NSBundle mainBundle] pathForResource:@"heros.plist" ofType:nil];
// 2.加载数组
NSArray *dictArray = [NSArray arrayWithContentsOfFile:path];
// 3.将dictArray里面的所有字典转成模型对象,放到新的数组中
NSMutableArray *heroArray = [NSMutableArray array];
for (NSDictionary *dict in dictArray) {
// 3.1.创建模型对象
MJHero *hero = [MJHero heroWithDict:dict];
// 3.2.添加模型对象到数组中
[heroArray addObject:hero];
}
// 4.赋值
_heros = heroArray;
}
return _heros;
}
相关文章推荐
- nagios监控端自动化安装脚本
- IOS 使用XML制作简易选择题
- iOS新手入门之点击空白处回收键盘
- iOS ----Block语法
- iOS开发关闭NSLog在控制台不能够输出
- iOS-Quartz 2D
- iOS 经典笔记
- iOS-真机调试
- iOS-AFN相较ASI
- iOS数据持久化
- iOS-ASI
- iOS开发-XIB、Storyboard操作小技巧
- iOS开发零基础教程之真机调试流程
- iOS开发- 处理空字符串
- autoresizesSubviews
- IOS开发——多线程
- 如何把设计图自动转换为iOS代码? 在线等,挺急的!
- iOS中使用正则表达式去掉HTML中的标签元素获得纯文本的方法
- IOS使用XMPP最新教程(四)获取好友列表 (通过花名册)
- AVAudioSession、AVAudioRecorder、AVAudioPlayer