每次在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
let array = NSArray(objects: "hangge.com","baidu.com","google.com","163.com","qq.com")
let filePath:String = NSHomeDirectory() + "/Documents/webs.plist"
array.writeToFile(filePath, atomically: true)

进入目录打开webs.plist,可以看到生成的数据如下:

1
2
3
4
5
6
7
8
9
10
11
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
    <string>hangge.com</string>
    <string>baidu.com</string>
    <string>google.com</string>
    <string>163.com</string>
    <string>qq.com</string>
</array>
</plist>
(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
import UIKit
 
class ViewController: UIViewController , UITableViewDelegate, UITableViewDataSource{
 
     
    @IBOutlet weak var tableView: UITableView!
     
    var webs:NSArray?
 
    override func viewDidLoad() {
        super.viewDidLoad()
         
        webs = NSArray(contentsOfFile: NSHomeDirectory() + "/Documents/webs.plist")
        self.tableView!.delegate = self
        self.tableView!.dataSource = self
        //创建一个重用的单元格
        self.tableView!.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell0")
    }
     
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return webs!.count
    }
     
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)
        -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell0",
            forIndexPath: indexPath) as UITableViewCell
        let url = webs![indexPath.row] as! String
        cell.textLabel?.text = url
        return cell
    }
 
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}
2,字典(Dictionary)的存储和读取 
下面给每条网址都附上网站名,这时我们就要使用字典了。
(1)存储
除了每条网站记录使用字典类型,外面还拆分成两个数组分别存储,用于下面表格的分区展示。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
let myArray = [
        [
            ["name":"航歌", "url":"hangge.com"],
            ["name":"百度", "url":"baidu.com"],
            ["name":"google", "url":"google.com"]
        ],
        [
            ["name":"163", "url":"163.com"],
            ["name":"QQ", "url":"qq.com"]
        ]
   //声明一个字典
         
let filePath:String = NSHomeDirectory() + "/Documents/webs.plist"
NSArray(array: myArray).writeToFile(filePath, atomically: true)
print(filePath)

进入目录打开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
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
    <array>
        <dict>
            <key>name</key>
            <string>航歌</string>
            <key>url</key>
            <string>hangge.com</string>
        </dict>
        <dict>
            <key>name</key>
            <string>百度</string>
            <key>url</key>
            <string>baidu.com</string>
        </dict>
        <dict>
            <key>name</key>
            <string>google</string>
            <key>url</key>
            <string>google.com</string>
        </dict>
    </array>
    <array>
        <dict>
            <key>name</key>
            <string>163</string>
            <key>url</key>
            <string>163.com</string>
        </dict>
        <dict>
            <key>name</key>
            <string>QQ</string>
            <key>url</key>
            <string>qq.com</string>
        </dict>
    </array>
</array>
</plist>
(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
import UIKit
 
class ViewController: UIViewController , UITableViewDelegate, UITableViewDataSource{
     
    @IBOutlet weak var tableView: UITableView!
     
    var webs:NSArray?
 
    override func viewDidLoad() {
        super.viewDidLoad()
         
        webs = NSArray(contentsOfFile: NSHomeDirectory() + "/Documents/webs.plist")
        self.tableView!.delegate = self
        self.tableView!.dataSource = self
        //创建一个重用的单元格
        self.tableView!.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell0")
 
    }
     
    // UITableViewDataSource协议中的方法,该方法的返回值决定指定分区的头部
    func tableView(tableView:UITableView, titleForHeaderInSection
        section:Int)->String?
    {
        return " ";
    }
     
    //在本例中,有2个分区
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return webs!.count;
    }
     
    //每个分区的记录数
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let data = self.webs?[section]
        return data!.count
    }
     
    //每个单元格创建和内容赋值
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)
        -> UITableViewCell {
        let cell = UITableViewCell(style: UITableViewCellStyle.Value1,
            reuseIdentifier: "cell0")
        let data = self.webs?[indexPath.section]
        let url = data![indexPath.row]["url"] as! String
        let name = data![indexPath.row]["name"] as! String
        cell.textLabel?.text = name
        cell.detailTextLabel?.text = url
        return cell
    }
 
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

原文出自:www.hangge.com  转载请保留原文链接:http://www.hangge.com/blog/cache/detail_888.html

Swift - .plist文件数据的读取和存储的更多相关文章

  1. CSV文件数据如何读取、导入、导出到新的CSV文件中以及CSV文件的创建

    CSV文件数据如何读取.导入.导出到新的CSV文件中以及CSV文件的创建 一.csv文件的创建 (1)新建一个文本文档: 打开新建文本文档,进行编辑. 注意:关键字与关键字之间用英文半角逗号隔开.第一 ...

  2. C语言进行csv文件数据的读取

    C语言进行csv文件数据的读取: #include <stdio.h> #include <string.h> #include <malloc.h> #inclu ...

  3. HDF 文件数据的读取

    http://www.cams.cma.gov.cn/cams_973/cheres_docs/cheres_doc_sat.modis.1b.html一. HDF文件格式 1.概述 HDF 是美国国 ...

  4. Python之TensorFlow的数据的读取与存储-2

    一.我们都知道Python由于GIL的原因导致多线程并不是真正意义上的多线程.但是TensorFlow在做多线程使用的时候是吧GIL锁放开了的.所以TensorFlow是真正意义上的多线程.这里我们主 ...

  5. 加载plist文件数据的方法

    这个pilist文件最外面的是一个数组,数组中每一个item是一个字典,我们的目的就是为了取到每一个item字典中的内容数据 下面看代码举例 //加载数组 - (void)handleData { / ...

  6. linux使用shell 进行文件数据的读取与排序

    题目 shell脚本语言编写一个从键盘输入10名学生(含自己)的姓名. 性别.学号和家庭住址,然后按照学号排序,并将排序后的结果在屏幕上按对齐 的方式打印输出的程序. 代码 读入数据 数据排序(这里用 ...

  7. ios本地文件内容读取,.json .plist 文件读写

    ios本地文件内容读取,.json .plist 文件读写 本地文件.json .plist文件是较为常用的存储本地数据的文件,对这些文件的操作也是一种常用的基础. 本文同时提供初始化变量的比较标准的 ...

  8. 黑马程序员——读取Plist文件

    -iOS培训,iOS学习-------型技术博客.期待与您交流!------------ 读取Plist文件     一:新建一个plist文件,并将plist文件数据填入plist文件中,这里pli ...

  9. Pandas_数据读取与存储数据(全面但不精炼)

    Pandas 读取和存储数据 目录 读取 csv数据 读取 txt数据 存储 csv 和 txt 文件 读取和存储 json数据 读取和存储 excel数据 一道练习题 参考 Numpy基础(全) P ...

随机推荐

  1. windows7 安装python

    首先去Python官网,https://www.python.org 找到downloads,我这里系统是win7 x64,下载的是最新版本3.4.2 下载完成后有个msi文件,选择文件安装目录,一路 ...

  2. Win7/8在用账户密码登录时, 设置成保留用户名, 只输入密码

    修改注册表, 0表示保留用户名. 1表示每次都需要输入用户名密码. 位置: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersio ...

  3. Android Activity和Intent机制学习笔记

    转自 http://www.cnblogs.com/feisky: Activity Android中,Activity是所有程序的根本,所有程序的流程都运行在Activity之中,Activity具 ...

  4. [Just a feeling]

    The possibility of enhancing one's knowledge is limitless. Graduation only marks a stage of one's ed ...

  5. 高质量程序设计指南C/C++语言——C++/C常量

  6. 面向对象程序设计-C++ Stream & Template & Exception【第十五次上课笔记】

    这是本门<面向对象程序设计>课最后一次上课,刚好上完了这本<Thinking in C++> :) 这节课首先讲了流 Stream 的概念 平时我们主要用的是(1)在屏幕上输入 ...

  7. Android 一个改进的okHttp封装库

    一.概述 之前写了篇Android OkHttp完全解析 是时候来了解OkHttp了,其实主要是作为okhttp的普及文章,当然里面也简单封装了工具类,没想到关注和使用的人还挺多的,由于这股热情,该工 ...

  8. 基于visual Studio2013解决C语言竞赛题之0401阶乘

      题目 解决代码及点评 这个是一道经典的教科书题目,基本上每本基础的c/c++语言教科书都会有这个题目 用来演示循环语句 #include <stdio.h> #include ...

  9. Uva 1103 Ancient Messages

    大致思路是DFS: 1. 每个图案所包含的白色连通块数量不一: Ankh : 1 ;  Wedjat : 3  ; Djed : 5   ;   Scarab : 4 ; Was : 0  ;  Ak ...

  10. 怎么在Ubuntu Scope中获取location地址信息

    Location信息对非常多有地址进行搜索的应用来说非常重要.比方对dianping这种应用来说.我们能够通过地址来获取当前位置的一些信息.在这篇文章中,我们来介绍怎样获取Scope架构中的位置信息. ...