171,.plist文件中字典数据转成程序模型
2016-01-04 13:35
357 查看
AppData.h:
#import <UIKit/UIKit.h>
@interface AppData :
NSObject
@property(nonatomic,copy)
NSString *name;
@property(nonatomic,copy)
NSString *icon;
//readonly就只会生成setter和getter方法,而不生成成员变量_image,所以,只能使用合成指令,定义_image。
@property(nonatomic,strong,readonly)
UIImage *image;
-(instancetype)initWithDic:(NSDictionary *)dic;
+(instancetype)appDataWithDic:(NSDictionary *)dic;
+(NSArray *)appList;
@end
AppData.m:
#import "AppData.h"
/*
使用KVC的注意事项
概念:全称(key value coding)键值编码,是一种简介修改/读取对象属性的一种方法
1,plist中的键值必须跟模型中的属性一致
2,模型中的属性个数可以等于或多个plist中的属性个数
*/
@implementation AppData
//合成指令,主动指定属性使用的成员变量名称
@synthesize image = _image;
-(UIImage *)image{
if (_image ==
nil) {
_image = [UIImage
imageNamed:self.icon];
}
return _image;
}
/**
* instancetype 主要用于在类方法实例化对象时,让编译器主动推断出对象的实际类型
*
*/
-(instancetype)initWithDic:(NSDictionary *)dic{
self = [super
init];
if (self) {
// 赋值第一种方法:
// self.name = dic[@"name"];
// self.icon = dic[@"icon"];
// 赋值第二种方法
// [self setValue:dic[@"name"] forKeyPath:@"name"];
// self setValue:dic[@"icon"] forKeyPath:@"icon"];
// 第三种方法的本质就是第二种方法的封装
[self
setValuesForKeysWithDictionary:dic];
}
return
self;
}
+(instancetype)appDataWithDic:(NSDictionary *)dic{
return [[self
alloc]initWithDic:dic];
}
+(NSArray *)appList{
NSString *path = [[NSBundle
mainBundle]pathForResource:@"app"
ofType:@".plist"];
NSArray *arr = [NSArray
arrayWithContentsOfFile:path];
NSMutableArray *dics = [[NSMutableArray
alloc]init];
for (int i=0; i<arr.count; i++) {
[dics addObject:[AppData
appDataWithDic:arr[i]]];
}
return dics;
}
@end
ViewController.h:
#import <UIKit/UIKit.h>
@class AppData;
@interface ViewController :
UIViewController
@end
ViewController.m:
#import "ViewController.h"
#import "AppData.h"
@interface
ViewController ()
@property(nonatomic,strong)
NSArray *appList;
@end
@implementation ViewController
-(NSArray *)appList{
if (_appList ==
nil) {
_appList = [AppData
appList];
}
return
_appList;
}
-(void)viewDidLoad{
[super
viewDidLoad];
for(int i =
0;i <self.appList.count;i++){
AppData *data =
self.appList[i];
NSLog(@"name = %@,icon = %@",data.name,data.icon);
}
for(int i =
0;i <self.appList.count;i++){
AppData *data =
self.appList[i];
UIImageView *image = [[UIImageView
alloc]initWithFrame:CGRectMake(0,
0, 200,
200)];
image.image =data.image;
[self.view
addSubview:image];
}
}
@end
相关文章推荐
- SAP R3 采购申请相关简单操作 :附Oracle后台数据库对应表明细。
- AngularJS 表格
- Jenkins入门系列之——02第二章 Jenkins安装与配置
- 设计模式(一)
- 利用C++11实现一个自动注册的工厂
- AndroidStudio快捷键(非复制粘贴)
- 源码安装mongoDB
- Mac环境下,numpy升级问题。
- codevs1796-最小完全图
- [新年好]新年第一贴,关于新增分区过程中遇到的问题
- linux echo命令-转
- ref传递
- Android:Service:服务的生命周期
- Mysql进程管理
- 【python】查看python的版本号
- OpenCV 计算均值方差
- 新的一年,新的开始
- exceptionininitializererror
- jstl数字转日期
- Xcode7 添加PCH文件