plist文件是以类似xml形式构造数据,下面我们直接在xcode中创建完成一个plist文件, File-New-File-属性列表

我们可以选择存储类型。这里我构造一组数据,数据中的每个元素都是一个字典,字典中存放着name songName imageName 三个键值。

这样我们的plist文件就完成了,下面来说一说通过kvc的方式来读取plist文件。

kvc的概念简单说下

Key-Value-Coding(KVC)键值编码

我们主要使用的是KVC字典转模型,将plist文件中的数据以数据模型的形式读取。

在构造数据模型时应当使用以下方法 直接设置

- (void)setValuesForKeysWithDictionary:(NSDictionary<NSString *, id> *)keyedValues;

下面构造一个StarModel

@interface StarModel : NSObject
//歌手名
@property(nonatomic,copy)NSString *name;
//歌曲名
@property(nonatomic,copy)NSString *songName;
//图片名
@property(nonatomic,copy)NSString *imageName;
//初始化
- (instancetype)initWithStarModelDict:(NSDictionary*)dict;
//类方法
+ (instancetype)starModelwithDict:(NSDictionary*)dict;
@end

下面设置初始化方法,将字典转为模型

@implementation StarModel

- (instancetype)initWithStarModelDict:(NSDictionary*)dict {
self = [super init];
if (self) {
//KVC 字典转模型
[self setValuesForKeysWithDictionary:dict];
}
return self;
}
+ (instancetype)starModelwithDict:(NSDictionary*)dict {
return [[StarModel alloc] initWithStarModelDict:dict];
}
@end

这样我们的模型就构造好了。下面来读取吧。

由于我们plist文件的根节点是一个数组

我们以懒加载的方式来创建这个数组,并将从plist中读取的字典信息以模型的形式存储到数组中。

//懒加载

- (NSMutableArray*)arrayAllModel {

    if (!_arrayAllModel) {
_arrayAllModel = [NSMutableArray array]; //获得路径并读取plist文件
NSString *starListPath = [[NSBundle mainBundle] pathForResource:@"starList" ofType:@"plist"];
NSArray *array= [NSArray arrayWithContentsOfFile:starListPath]; for (NSDictionary *dic in array) {
StarModel *star = [StarModel starModelwithDict:dic];
//存储所有结果
[_arrayAllModel addObject:star];
}
}
return _arrayAllModel;
}

大功告成。现在我们的数组中就都是存放了这些数据模型了。

测试一下数据吧。

 for (StarModel *model in self.arrayAllModel) {
NSLog(@"%@,%@,%@",model.name,model.songName,model.imageName);
}

最新文章

  1. CSS背景图像位置属性background-position百分比详解
  2. maven总结3
  3. 微信也能鉴别山寨iPhone【微信高级教程2】
  4. fiddlercore 抓包获取cookie的方法
  5. 简单的访客IP获取类-IPHelper.cs
  6. 【字母树+贪心】【HDU3460】【Ancient Printer】
  7. ldap数据库--ODSEE--schema
  8. String去重方法
  9. 【jpa】spring data jpa 配置使用
  10. Windows网络发现无法启动
  11. 万里长征第一步:Python进程池的一点点小坑
  12. Spring整合redis配置文件详解
  13. hive使用python脚本导致java.io.IOException: Broken pipe异常退出
  14. 012-Future、FutureTask、CompletionService 、CompletableFuture
  15. P1312 Mayan游戏
  16. 2018年全国多校算法寒假训练营练习比赛(第一场)C 六子冲
  17. English trip -- VC(情景课)8 C
  18. Hive分区表创建,增加及删除
  19. Node.js API学习笔记(一)
  20. SCSI, (P)ATA, SAS, NL-SAS and SATA, what’s the difference?

热门文章

  1. 关于eclipse新建web项目,提示:&quot;The superclass &quot;javax.servlet.http.HttpServlet&quot; was not found on the Java&quot;解决办法
  2. ActiveMQ 和消息简介
  3. [0] 分析 EntityName 时出错。 行 2,位置 *。
  4. javaScript的一些奇妙动画
  5. VR虚拟现实技术在教育领域的前景展望
  6. 初玩RAC
  7. spingMVC aop不生效的解决方式
  8. 【Netty】TCP粘包和拆包
  9. Linux编程之epoll
  10. docker中执行sed: can&#39;t move &#39;/etc/resolv.conf73UqmG&#39; to &#39;/etc/resolv.conf&#39;: Device or resource busy错误的处理原因及方式