Objective-C plist文件与KVC 的使用
2024-10-11 14:21:37
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);
}
最新文章
- CSS背景图像位置属性background-position百分比详解
- maven总结3
- 微信也能鉴别山寨iPhone【微信高级教程2】
- fiddlercore 抓包获取cookie的方法
- 简单的访客IP获取类-IPHelper.cs
- 【字母树+贪心】【HDU3460】【Ancient Printer】
- ldap数据库--ODSEE--schema
- String去重方法
- 【jpa】spring data jpa 配置使用
- Windows网络发现无法启动
- 万里长征第一步:Python进程池的一点点小坑
- Spring整合redis配置文件详解
- hive使用python脚本导致java.io.IOException: Broken pipe异常退出
- 012-Future、FutureTask、CompletionService 、CompletableFuture
- P1312 Mayan游戏
- 2018年全国多校算法寒假训练营练习比赛(第一场)C 六子冲
- English trip -- VC(情景课)8 C
- Hive分区表创建,增加及删除
- Node.js API学习笔记(一)
- SCSI, (P)ATA, SAS, NL-SAS and SATA, what’s the difference?
热门文章
- 关于eclipse新建web项目,提示:";The superclass ";javax.servlet.http.HttpServlet"; was not found on the Java";解决办法
- ActiveMQ 和消息简介
- [0] 分析 EntityName 时出错。 行 2,位置 *。
- javaScript的一些奇妙动画
- VR虚拟现实技术在教育领域的前景展望
- 初玩RAC
- spingMVC aop不生效的解决方式
- 【Netty】TCP粘包和拆包
- Linux编程之epoll
- docker中执行sed: can&#39;t move &#39;/etc/resolv.conf73UqmG&#39; to &#39;/etc/resolv.conf&#39;: Device or resource busy错误的处理原因及方式