【问题标题】:Swift .writeToFile does not update JSON file in mainBundleSwift .writeToFile 不会更新 mainBundle 中的 JSON 文件
【发布时间】:2015-02-16 12:11:30
【问题描述】:

我正在尝试一个简单的字典检索、更新键值并写回文件。由于某种原因,writeToFile 不会更新主包中的文件。

代码如下:

let filename = "testFile"
if let path = NSBundle.mainBundle().pathForResource(filename, ofType: "json") {
    var error: NSError?
    let InputData: NSData? = NSData(contentsOfFile: path, options: NSDataReadingOptions(), error: &error)
    var jsonDictionary: NSMutableDictionary = NSJSONSerialization.JSONObjectWithData(InputData!, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSMutableDictionary

    jsonDictionary.setValue(1, forKey: "levelRow")

    let options = NSJSONWritingOptions.PrettyPrinted
    var outputData : NSData? =  NSJSONSerialization.dataWithJSONObject(jsonDictionary, options: options, error: &error)

    outputData?.writeToFile(path, atomically: true)
}

文件如下所示:

{
    "levelColumn" : 0,
    "levelRow" : 0,
}

读取和更新工作正常...但文件没有将 levelRow 更新为 1?

提前致谢。

【问题讨论】:

  • 不能在bundle里面写资源,使用Cache或者Documents目录保存程序数据

标签: ios json swift


【解决方案1】:

您不能写入主包。捆绑包中的所有文件都是只读的。在修改之前将您的文件复制到应用程序文档目录中。

如果您需要在应用程序中包含捆绑包中的其他文件,您可以在开发期间在文档目录中更新它,然后在发布您的应用程序之前手动将其复制到捆绑包中。

【讨论】:

  • 感谢您的快速响应。新手(如您所见!)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-31
  • 2020-04-08
  • 1970-01-01
  • 2017-05-04
相关资源
最近更新 更多