在项目中可能我们需要保存一些数据到plist文件中,以下就本人在学习过程中的笔记,不成熟的地方请指出。
可能我有一个类叫做Student
import UIKit
class Student: NSObject {
var text:String
var age:Bool
init(text:String,age:Int) {
self.text = text
self.age = age
}
//从nsobject中解析回来
init(coder aDecoder:NSCoder){
self.text = aDecoder.decodeObjectForKey("Text") as! String
self.age = aDecoder.decodeObjectForKey("Age") as! Int
}
//编码成object
func encodeWithCoder(aCoder:NSCoder){
aCoder.encodeObject(text, forKey: "Text")
aCoder.encodeObject(checked, forKey: "Age")
}
}
encodeWithCoder方法中,每一个属性设置为一个关键字,用于序列化编码,以便我们在init(coder aDecoder:NSCoder)中解析回来
以下是两个保存用加载plist数据的方法
var students:[Student] = [Student]()
func loadStudentsData() {
let path = self.dataFilePath()
//声明文件管理器
let defaultManager = NSFileManager()
if defaultManager.fileExistsAtPath(path) {
let data = NSData(contentsOfFile: path)
//解码器
let archive = NSKeyedUnarchiver(forReadingWithData: data!)
students = archive.decodeObjectForKey("Students") as! Array
//结束解码
archive.finishDecoding()
} else {
saveStudentsData()
}
}
func saveStudentsData() {
var data = NSMutableData()
//聲明一個歸檔處理對象
var archive = NSKeyedArchiver(forWritingWithMutableData: data)
//將arrData進行編碼
archive.encodeObject(students, forKey: "Students")
archive.finishEncoding()
//數據寫入
data.writeToFile(dataFilePath(), atomically: true)
}
在UI启动的时候加入loadStudentsData()方法,每次有改变students数组的时候调用saveStudentsData()方法