Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
985 views
in Technique[技术] by (71.8m points)

ios - Swift .writeToFile does not update JSON file in mainBundle

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.

the code reads:

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)
}

the file looks like this:

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

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

thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...