plist文件的读写这部分有个坑,在Xcode中创建的plist文件在代码运行时是只读的,你可以正确写入读出,但是无法持久化存储。如果想做持久化,必须用代码在沙箱目录中创建plist文件。因为Xcode创建的plist文件和程序代码同级,就如同你无法在运行时修改程序代码。
读取Xcode中手动创建的Plist文件
let plistPath = Bundle.main.path(forResource: "demoPlist", ofType: "plist")
let data:NSMutableDictionary = NSMutableDictionary.init(contentsOfFile: plistPath!)!
let message = data.description
print(message)
在程序沙箱目录中创建可持久化存储的plist文件
let path = NSHomeDirectory() + "/Documents/testPlist.plist"
if let dic:NSMutableDictionary = NSMutableDictionary.init(contentsOfFile: path) {
let message = dic.description
print(message)
} else {
let filemanger = FileManager.default
let dictionary:NSDictionary = ["name":"chen chao", "age":"18", "info":"Good Teacher"]
do {
let data = try PropertyListSerialization.data(fromPropertyList: dictionary, format: .xml , options: .zero)
filemanger.createFile(atPath: path, contents: data, attributes: nil)
} catch {
print("error")
}
}