每次在Xcode中新建一个iOS项目后,都会自己产生一个.plist文件,里面记录项目的一些配置信息。我们也可以自己创建.plist文件来进行数据的存储和读取。
.plist文件其实就是一个XML格式的文件,其支持的数据类型有(NS省略)Dictionary、Array、Boolean、Data、Date、Number、String这些类型。
当然对于用户自定义的对象,通过NSCoder转换后也是可以进行存储的。(常见我的另一篇文章“Swift - 本地数据的保存与加载(使用NSCoder将对象保存到.plist文件)”)
本文主要介绍如何使用.plist文件进行数组,字典,字符串等这些基本数据类型的存储和读取。
由于不需要转化,所以用起来还是很方便的。而且在大多数情况下,使用基本数据类型就足够了。
1,数组(Array)的存储和读取
(1)存储
下面把一个数组写入plist文件中(保存在用户文档目录),数组内是各个网站的地址。
1 2 3 | |
进入目录打开webs.plist,可以看到生成的数据如下:
1 2 3 4 5 6 7 8 9 10 11 | |
(2)读取
下面把webs.plist文件中数据读取出来显示在表格里
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
|
2,字典(Dictionary)的存储和读取
下面给每条网址都附上网站名,这时我们就要使用字典了。
(1)存储
除了每条网站记录使用字典类型,外面还拆分成两个数组分别存储,用于下面表格的分区展示。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
进入目录打开webs.plist,可以看到生成的数据如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | |
(2)读取
下面把webs.plist文件中数据读取出来,并在表格里分区显示
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
|