iOS高质量博客iOSiOS开发基础篇

iOS开发,plist文件读写那些事

2016-09-29  本文已影响17067人  林夕不昔

什么是plist文件?

一、创建plist文件

创建plist文件

然后就是给文件命名:

plist文件命名

这里有一点需要注意:
命名的时候不能用Info.plist , INfo.plist, xxxInfo.plist等形式,否则会出现下面的情况,因为系统中存在一个Info.plist文件,会发生冲突。

命名中包含info的情况

上图中的plist文件只能是NSDictionary类型,而且添加数据时会出现如下的情况:

添加数据

通常情况下,我们想要的并不是这种效果,所以命名的时候要注意。通常我们想要的plist文件是下图中的样子:

在Root这一行,Type可以选择字典或数组。


命名规范的情况

点击Root这一行,然后通过点击右键->Add Row或者点击Root后面的加号来增加一行。这一行中包含三个属性,key、type、value。其中key是字段属性,type是字段类型,value是字段对应的值。而Type又包含7中类型,其中两种是Array和Dictionary,这两种是数组的形式,在它们下面还可以包含许多key-value。

而另外5种是Boolean,data,string,date,number。这5种类型的数据都是被array和dictionary所要包含的数据。


添加数据并赋值
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

获取完整路径

NSString *documentsPath = [path objectAtIndex:0];
  NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"newsTest.plist"];

创建数据

//创建数据
NSMutableDictionary *newsDict = [NSMutableDictionary dictionary];
//赋值
[newsDict setObject:@"zhangsan" forKey:@"name"];
[newsDict setObject:@"12" forKey:@"age"];
[newsDict setObject:@"man" forKey:@"sex"];

写入plist文件

[newsDict writeToFile:plistPath atomically:YES];

二、读取plist文件

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"newsModel" ofType:@"plist"];

代码方式创建的plist文件获取其路径的方式如下:

NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path1 = [pathArray objectAtIndex:0];
 NSString *myPath = [path1 stringByAppendingPathComponent:@"newsTest.plist"];
//newsModel.plist文件
NSMutableArray *data1 = [[NSMutableArray alloc] initWithContentsOfFile:filePath];
//newsTest.plist文件
NSMutableDictionary *data2 = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];

数据输出如下:

数据输出

三、添加数据

同样是先获取路径,注意获取路径的方式视情况而定:

//用新建文件的方式常见的plist文件,获取其路径
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"newsModel" ofType:@"plist"];
//代码方式创建的plist文件获取其路径
NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path1 = [pathArray objectAtIndex:0];
NSString *myPath = [path1 stringByAppendingPathComponent:@"newsTest.plist"];

然后是取到数据:

//newsModel.plist文件
NSMutableArray *data1 = [[NSMutableArray alloc] initWithContentsOfFile:filePath];
//newsTest.plist文件
NSMutableDictionary *data2 = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];

对数据进行操作,添加数据:

//新建一个字典,设置属性值
NSMutableDictionary *addData1 = [NSMutableDictionary dictionary];
[addData1 setObject:@"123" forKey:@"title"];
[addData1 setObject:@"pic.png" forKey:@"image"];
[addData1 setObject:@"wobushi" forKey:@"detail"];
//添加到数组中
[data1 addObject:addData1];
//写入文件
[data1 writeToFile:filePath atomically:YES];
//增加一个字段”job“,并设置属性值
[data2 setObject:@"writer" forKey:@"job"];
//写入文件
[data2 writeToFile:plistPath atomically:YES];

修改后的数据输出如下:

添加数据

以上就是plist文件的常用操作,当然,还可以进行修改删除等操作,方法类似,这里就不做描述了。

上一篇下一篇

猜你喜欢

热点阅读