【发布时间】: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目录保存程序数据