Swift .writeToFile不会更新mainBundle中的JSON文件 [英] Swift .writeToFile does not update JSON file in mainBundle

查看:252
本文介绍了Swift .writeToFile不会更新mainBundle中的JSON文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying a simple dictionary retrieve, update key value and write back to file. For some reason the writeToFile does not update the file in the main bundle.

代码为:

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?

the read and update work fine... but the file doe not update levelRow to 1?

提前感谢。

推荐答案

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

You cannot write to the main bundle. All files in the bundle are read-only. Copy your file into the application documents directory before modifying it.

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

If you need a different file in the bundle to include in your application, you can update it in the documents directory during development and then manually copy it to the bundle before shipping your app.

这篇关于Swift .writeToFile不会更新mainBundle中的JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆