我正在尝试用Xcode写一个plist。除了plist文件没有改变外,我写的东西都起作用了。我尝试了几个不同的实现,得到了相同的结果。
代码如下:
func saveGameData() {
let BedroomFloorKey = "BedroomFloor"
let BedroomWallKey = "BedroomWall"
var bedroomFloorID: AnyObject = 101 as AnyObject
var bedroomWallID: AnyObject = 101 as AnyObject
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as NSArray
let documentsDirectory = paths.object(at: 0) as! NSString
let path = documentsDirectory.appendingPathComponent("room.plist")
print("PATH", path)
let dict: NSMutableDictionary = ["XInitializerItem": "DoNotEverChangeMe"]
//saving values
dict.setObject(bedroomFloorID, forKey: BedroomFloorKey as NSCopying)
dict.setObject(bedroomWallID, forKey: BedroomWallKey as NSCopying)
//...
//writing to GameData.plist
dict.write(toFile: path, atomically: false)
let resultDictionary = NSMutableDictionary(contentsOfFile: path)
print("Saved GameData.plist file is --> \(resultDictionary?.description ?? "")")
}
我的plist位于xcode项目的主目录中,与ViewController所在的文件夹相同。
谢谢
由于明显的原因,您无法写入应用程序包,该包是只读的。
您的代码将plist写入应用程序容器中的documents
目录。如果应用程序包中有一个默认属性列表文件,那么在应用程序首次启动时将其复制到Documents目录中。
然而,这段代码看起来像Objective-C代码的一个丑陋的直译。这是本地Swift版本
func saveGameData() throws {
let bedroomFloorKey = "BedroomFloor"
let bedroomWallKey = "BedroomWall"
let bedroomFloorID = 101
let bedroomWallID = 101
let documentsDirectory = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let url = documentsDirectory.appendingPathComponent("room.plist")
print("PATH", url)
var dict : [String:Any] = ["XInitializerItem": "DoNotEverChangeMe"]
//saving values
dict[bedroomFloorKey] = bedroomFloorID
dict[bedroomWallKey] = bedroomWallID
//...
//writing to GameData.plist
let data = try PropertyListSerialization.data(fromPropertyList: dict, format: .xml, options: 0)
try data.write(to: url)
print("Saved GameData.plist file is --> \(dict)")
}
不需要重读数据。如果没有抛出错误,则plist已成功写入。
在文档中创建plist文件
let path = documentsDirectory.appendingPathComponent("room.plist")
与位于主包中的文件不同(与viewcontroller.swift
级别相同),该文件将不接受任何写入,因为包与应用程序签名,并且不能接受任何更改