天天看点

iOS开发之数据存储之XML属性列表(plist)归档

1、概述

“归档”意思是持久化存储数据。plist文件是一种xml格式的文件,拓展名为plist。如果对象是nsstring、nsdictionary、nsarray、nsdata、nsnumber等类型,就可以使用writetofile:atomically:方法直接将对象写到属性列表文件(plist文件)中。特别注意的是plist文件不能存储对象。

ios常用文件存储方式有:

xml属性列表(plist)归档

preference(偏好设置)

nskeyedarchiver归档(nscoding)

sqlite3

core data

2、归档nsdictionary

将一个nsdictionary对象归档到一个plist属性列表中:

首先,将数据封装成字典:

nsmutabledictionary *dict = [nsmutabledictionary dictionary];

[dict setobject:@"母鸡" forkey:@"name"];

[dict setobject:@"15013141314" forkey:@"phone"];

[dict setobject:@"27" forkey:@"age"];

其次,获取沙盒中documents/stu.plist完整路径,根据路径将字典持久化到documents/stu.plist文件中:

[dict writetofile:path atomically:yes];//yes代表安全存储

成功写入到documents目录下后如下图:

iOS开发之数据存储之XML属性列表(plist)归档

用文本编辑器打开,文件内容如下图:

iOS开发之数据存储之XML属性列表(plist)归档

用xcode打开属性文件如下图:

iOS开发之数据存储之XML属性列表(plist)归档

上面是从nsdictionary写入到plist文件,也可以从nsarray写入到plist文件,例如:

// 1.获得沙盒根路径

nsstring *home = nshomedirectory();

// 2.拼接成document路径

nsstring *docpath =

[home stringbyappendingpathcomponent:@"documents"];

// 3.新建数据

nsarray *data = @[@"jack", @10, @"ffdsf"];

//4.拼接成具体文件的路径

nsstring *filepath =

[docpath stringbyappendingpathcomponent:@"data.plist"];

// 5.写入数据

[data writetofile:filepath atomically:yes];

3、恢复nsdictionary

读取documents/stu.plist的内容,实例化nsdictionary

nsdictionary *dict = [nsdictionary dictionarywithcontentsoffile:path];

nslog(@"name:%@", [dict objectforkey:@"name"]);

nslog(@"phone:%@", [dict objectforkey:@"phone"]);

nslog(@"age:%@", [dict objectforkey:@"age"]);

打印信息如下:

iOS开发之数据存储之XML属性列表(plist)归档

上面是读取到nsdictionary,对应地,我们也可以读取到nsarray,例如:

// 2.document路径

// 3.文件路径

// 4.读取数据

nsarray *data = [nsarray arraywithcontentsoffile:filepath];

4、nsdictionary的存储和读取过程

iOS开发之数据存储之XML属性列表(plist)归档