
作为IOS开发初级者今天学习了 如何将plist数据字典转成 数据对象数组中 。有点像C#中解析xml数据 的过程。
apps.plist的xml数据是这样的
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PRopertyList-1.0.dtd">
<plist version="1.0">
<array>
<dict>
<key>name</key>
<string>天天酷跑</string>
<key>icon</key>
<string>icon_00</string>
</dict>
<dict>
<key>name</key>
<string>保卫萝卜2</string>
<key>icon</key>
<string>icon_10</string>
</dict>
<dict>
<key>name</key>
<string>神偷奶爸</string>
<key>icon</key>
<string>icon_11</string>
</dict>
</array>
</plist>
从处理plist中的数据 并返回模型对象的数组
/**
* 从处理plist中的数据 并返回模型对象的数组
*
* @return NSArray *apps;
*/
-(NSArray *) apps{
if (_apps==nil) {
// 过去plist的全路径
NSString *path=[[NSBundle mainBundle]pathForResource:@"app.plist" ofType:nil];
//加载数组
NSArray *dicArray=[NSArray arrayWithContentsOfFile:path];
//将dicArray里面的所有字典转成模型对象,放到新的数组中。
NSMutableArray *appArray=[NSMutableArray array];
for (NSDictionary *dict in dicArray) {
//创建模型对象
/*
MyApp *app=[[MyApp alloc] initWithDict:dict];
[NSString stringWithFormat:<#(NSString *), ...#>];
[[NSString alloc] initWithFormat:<#(NSString *), ...#>];
[NSArray arrayWithContentsOfFile:<#(NSString *)#>]
[[NSArray alloc] initWithContentsOfFile:<#(NSString *)#>;
通过这里 我们需要提取一个appWith
一个命名规范的问题
*/
MyApp *app=[MyApp appWithDict:dict];
//添加到对象到数组中
[appArray addObject:app];
}
//赋值
_apps=dicArray;
}
return _apps;
}
自定义的MyApp类,和字典中做到一一对应
#import <Foundation/Foundation.h>
/**
* copy :NSString
strong :一般对象
weak:UI控件
assign :基本数据类型
*/
@interface MyApp : NSObject
/**
* 图标
*/
@property (nonatomic,copy) NSString *icon;
/**
* 名称
*/
@property(nonatomic,copy) NSString *name;
/**
* 通过字典来初始化模型对象
*
* @param dic 字典对象
*
* @return 已经初始化完毕的模型对象
*/
/*
instancetype的作用,就是使那些非关联返回类型的方法返回所在类的类型!
好处能够确定对象的类型,能够帮助编译器更好的为我们定位代码书写问题
instanchetype和id的对比 1、相同点 都可以作为方法的返回类型 2、不同点 ①instancetype可以返回和方法所在类相同类型的对象,id只能返回未知类型的对象; ②instancetype只能作为返回值,不能像id那样作为参数,比如下面的写法: */ -(instancetype)initWithDict:(NSDictionary *)dict; +(instancetype) appWithDict:(NSDictionary *)dict; @end
@implementation MyApp
-(instancetype)initWithDict:(NSDictionary *)dict{
if (self=[super init]) {
self.name=dict[@"name"];
self.icon=dict[@"icon"];
}
return self;
}
+(instancetype) appWithDict:(NSDictionary *)dict{
// 为何使用self,谁调用self方法 self就会指向谁!!
return [[self alloc] initWithDict:dict];
}
@end