博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Objective-C plist文件与KVC 的使用
阅读量:4679 次
发布时间:2019-06-09

本文共 1878 字,大约阅读时间需要 6 分钟。

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

创建plist.png

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

plist构造数据.png

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

kvc的概念简单说下

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

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

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

- (void)setValuesForKeysWithDictionary:(NSDictionary
*)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);    }

测试数据.png

转载于:https://www.cnblogs.com/gongxiaokai/p/7123815.html

你可能感兴趣的文章
[stm32] 中断
查看>>
L1-043 阅览室
查看>>
我大学时代的好朋友要结婚了!
查看>>
RTP Payload Format for Transport of MPEG-4 Elementary Streams over http
查看>>
PAT-1134. Vertex Cover (25)
查看>>
git 命令图解
查看>>
分布式存储系统可靠性系列三:设计模式
查看>>
this关键字的由来及使用
查看>>
两个时间相差多少 .net中的timespan应用
查看>>
递归 换零钱问题——由打靶子问题引申
查看>>
Python-函数基础
查看>>
Extensible Messaging and Presence Protocol (XMPP) 简介
查看>>
Farm Irrigation
查看>>
windows平板的开发和选型
查看>>
无平方因子的数(数论初步) By ACReaper
查看>>
C语言截取字符串
查看>>
如何查自己的账单
查看>>
JAVA8学习笔记(二)----三个预定义接口
查看>>
JDBC连接各种数据库的字符串
查看>>
构建之法阅读笔记06
查看>>