plist 文件在 swift 1.2 中写入,但在 swift 2.0 中无法写入或工作,我该怎么办?

plist file gets written in swift 1.2 but its not get written or works in swift 2.0, what should i do?

我在使用 swift 1.2 时写了一段代码,它的功能是从 plist 加载和保存数据。它在 swift 1.2 上工作正常,但现在我在 swift 2 上工作。代码仍然加载值但不保存值。 i 运行 设备上的应用程序而不是模拟器。

您可以看到下面的代码:

 func loadGameData() {

    let path = NSBundle.mainBundle().pathForResource("GameData", ofType: "plist")!

    let myDict = NSDictionary(contentsOfFile: path)

    if let dict = myDict {

        highscore = dict.objectForKey("highscore")!


    } else {
        print("WARNING: Couldn't create dictionary from GameData.plist! Default values will be used!")
    }
}

func saveGameData() {
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
    let documentsDirectory = paths.objectAtIndex(0) as! NSString
    let path = documentsDirectory.stringByAppendingPathComponent("GameData.plist")
    let dict: NSMutableDictionary = ["XInitializerItem": "DoNotEverChangeMe"]



    dict.setObject(highscore.integerValue, forKey: "highscore")

    //writing to GameData.plist

    dict.writeToFile(path, atomically: true)

    let resultDictionary = NSMutableDictionary(contentsOfFile: path)
    print("Saved GameData.plist file is --> \(resultDictionary?.description)")

}

保存代码后的控制台消息是:

Saved GameData.plist file is --> Optional("{\n    XInitializerItem = DoNotEverChangeMe;\n    highscore = 25;\n}")

有人知道与 swift 2 一起使用的不同代码吗?这个与以前的版本配合得很好。

谢谢帮助

问题是您在直接写入 Documents 的同时从 Main bundle 读取。

阅读路径: NSBundle.mainBundle().pathForResource("GameData", ofType: "plist")!

写入路径: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray

要解决此问题,请将您的 reader 代码更改为:

func loadGameData() {
   let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
   let documentsDirectory = paths.objectAtIndex(0) as! NSString
   let path = documentsDirectory.stringByAppendingPathComponent("GameData.plist")

   let myDict = NSDictionary(contentsOfFile: path)

   if let dict = myDict {
      highscore = dict.objectForKey("highscore")!
   } else {
      print("WARNING: Couldn't create dictionary from GameData.plist! Default values will be used!")
   }
}