Add/Edit JSON data iOS?

后端 未结 2 1848
你的背包
你的背包 2021-02-11 10:39

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

2条回答
  •  Happy的楠姐
    2021-02-11 11:13

    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];
    

提交回复
热议问题