I am using the below code to fetch JSON data from my local drive. It works quite well
Now I want to add my JSON data to the Same URL
I don\'t w
If the file is part of the app bundle, you can't change anything about it.
Generally speaking you do want to replace the existing file.
While you could use NSFileHandle
to write additional data into the file it is relatively complex and relatively likely to corrupt the JSON (when you make an indexing mistake or something like that).
Your best option is to read the data in mutable (as you are), then modify and use NSJSONSerialization
to convert back to data again, then save that data to disk (replacing the original).
Your current code should really be:
NSMutableArray* json = [...
because of the mutable container option you're using.
You can then add some new items to the array:
[json addObject:@"Stuff"];
[json insertObject:@"Other Stuff" atIndex:0];
Then re-save:
data = [NSJSONSerialization dataWithJSONObject:json options:nil error:&error];
[data writeToURL:fileUrl atomically:YES];