前言:iOS的属性文件(Property List)是以.plist结尾,以文件形式存储信息。我通常会创建一个根字典rootDict,然后把需要的各种格式数据根据Key写进根字典保存起来,需要的时候再根据对应的Key把数据提出来。当然,文件只保存少量关键数据,APP退出也不会影响到的数据。
1. 文件路径-通常放在沙盒中的Documents文件夹中
//工程中(私有的沙箱目录)" Data.plist "文件的路径
let DataPlistPath: String! = Bundle.main.path(forResource: "Data", ofType: "plist")
//初始化localData.plist文件的路径;NSHomeDirectory:应用所存储的目录
let localPlistPath: String! = NSHomeDirectory() + "/Documents/localData.plist"
2. 初始化属性列表文件
func createEditableFileIfNeeded() {
//根据localPlistPath判断localData.plist文件是否存在
let fileManager = FileManager.default
let dbexits = fileManager.fileExists(atPath: self.localPlistPath)
if !dbexits {
//如果文件不存在则创建localData.plist文件
fileManager.createFile(atPath: self.localPlistPath, contents: nil, attributes: nil)
//初始化字典
initData()
}
}
3. 初始化数据
func initData() {
//将字典类型的数据写入localData.plist
let rootDict = NSMutableDictionary()
//设置bool
rootDict.setValue(true, forKey: "key_Bool")
//设置array
rootDict.setValue(["one","two"], forKey: "key_Array")
//设置numberInt
rootDict.setValue(1, forKey: "key_Int")
//设置numberFloat
rootDict.setValue(1.2, forKey: "key_Float")
//设置dictionary
rootDict.setValue(["key1":"value1","key2":"value2"], forKey: "key_Dictionary")
//设置date
rootDict.setValue(NSDate(), forKey: "key_Date")
//将rootDict写入localData.plist文件
rootDict.write(toFile: self.localPlistPath, atomically: true)
}
4. 读取localData.plist里的数据
func readData(key:String) -> String? {
let rootDict = NSMutableDictionary(contentsOfFile: self.localPlistPath)
let data = rootDict?[key] as? String
return data
}
5. 更新数据(修改读取到的rootDict,再把rootDict重新写入localData.plist)
func updateData(key:String, data:String) {
let rootDict = NSMutableDictionary(contentsOfFile: self.localPlistPath)
rootDict?.setValue(data, forKey: key)
rootDict?.write(toFile: self.localPlistPath, atomically: true)
}