Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
980 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...