您的位置:首页 > 其它

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



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: