Swift数据持久化 - 属性列表(plist)

iOS中数据持久化有plist,NSUserDefualt,SQLData和Core Data几种方式。本文结合上一篇Swift单例模式Singleton pattern的实现来创建一个基于plist的数据持久化单例。

plist储存入门

属性列表(plist)是一种XML文件,Foundation框架中数组和字典等都可以与plist文件相互转换。比如下文就是一个标准的plist文件,保存了一组array["衣带渐宽终不悔","为伊消得人憔悴","故国不堪回首明月中","人生若只如初见","暮然回首,那人却在灯火阑珊处"]

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>衣带渐宽终不悔</string>
<string>为伊消得人憔悴</string>
<string>故国不堪回首明月中</string>
<string>人生若只如初见</string>
<string>暮然回首,那人却在灯火阑珊处</string>
</array>
</plist>

数据写入plist

可以通过一下函数把一组数组写入plist,写入plist后就算退出数据也会保存,直到手动删除。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
func saveWithFile() {
/// 1、获得沙盒的根路径
let home = NSHomeDirectory() as NSString;
/// 2、获得Documents路径,使用NSString对象的stringByAppendingPathComponent()方法拼接路径
let docPath = home.stringByAppendingPathComponent("Documents") as NSString;
/// 3、获取文本文件路径
let filePath = docPath.stringByAppendingPathComponent("data2.plist");
var dataSource = NSMutableArray();
dataSource.addObject("衣带渐宽终不悔");
dataSource.addObject("为伊消得人憔悴");
dataSource.addObject("故国不堪回首明月中");
dataSource.addObject("人生若只如初见");
dataSource.addObject("暮然回首,那人却在灯火阑珊处");
/// 4、将数据写入文件中
dataSource.writeToFile(filePath, atomically: true);
/// 5、输出沙盒路径
println("\(filePath)");
}

读取plist

不管写入还是读取,都要先获取软件本身的沙盒路径,再从路径中找出具体文件的路径,从而进行读写。

1
2
3
4
5
6
7
8
9
10
func readWithFile() {
/// 1、获得沙盒的根路径
let home = NSHomeDirectory() as NSString;
/// 2、获得Documents路径,使用NSString对象的stringByAppendingPathComponent()方法拼接路径
let docPath = home.stringByAppendingPathComponent("Documents") as NSString;
/// 3、获取文本文件路径
let filePath = docPath.stringByAppendingPathComponent("data.plist");
let dataSource = NSArray(contentsOfFile: filePath);
println("\(dataSource)");
}

FileManager 单例创建

创建单例

按照Swift单例模式Singleton pattern的实现第三种方法,创建数据管理单例。

1
2
3
4
5
6
7
private let _SingletonASharedInstance = DataManager()

class DataManager {
class var sharedInstance : DataManager {
return _SingletonASharedInstance
}
}

重构代码

不管读取还是写入,都有一个重复的过程就是获取文件路径,所以重构代码为如下

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
import Foundation

private let _SingletonASharedInstance = DataManager()

class DataManager {

/// 创建单例
class var sharedInstance : DataManager {
return _SingletonASharedInstance
}

/// 获取文件路径
func filePath(filename: String) -> String {
var mypaths:NSArray = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
var mydocpath:String = mypaths.objectAtIndex(0) as! String
var filepath = mydocpath.stringByAppendingPathComponent(filename)
return filepath
}

/// 初始化数据
func saveWithFile() {
let filePath = self.filePath("data.plist")
var dataSource = NSMutableArray()
dataSource.writeToFile(filePath, atomically: true)
println("\(filePath)")
}

/// 增加数据
func appendData(newData:String) {
var filename = self.filePath("data.plist")
let dataSource = NSArray(contentsOfFile: filename as String) as! NSMutableArray
dataSource.addObject(newData)
dataSource.writeToFile(filename as String, atomically: true)
}

/// 增加数据
func readWithFile() {
let filePath = self.filePath("data.plist")
let dataSource = NSArray(contentsOfFile: filePath)
println("\(dataSource)")
}

/// 删除数据
func deleleWithFile() {
let filePath = self.filePath("data.plist")
let dataSource:NSMutableArray = []
dataSource.writeToFile(filePath, atomically: true)
}
}

###用法

1
2
3
DataManager.sharedInstance.appendData("string~~")
DataManager.sharedInstance.readWithFile()
DataManager.sharedInstance.deleleWithFile()

参考