简体   繁体   中英

writeToFile is overwriting the previous data

I'm using writeToFile property of NSDictionary in my code i'm trying to update a dictionary to documents directory like below,

NSDictionary *revisionDict = [NSDictionary dictionaryWithObject:currentItem.rev forKey:destPath];
NSArray *documentDirPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentDirPath objectAtIndex:0];
NSString *dictPath = [documentsDir stringByAppendingPathComponent:@"Revision.dictionary"];
[revisionDict writeToFile:dictPath atomically:YES];

here the problem is my dictionary rather than getting updated by new entries on each iteration it is getting overwitten by new entry. How can i update my dictionary is there any alternate for writeToFile, Any help is appreciated in advance.

A dictionary in memory can be mutable; a dictionary written to disk is a snapshot of a complete set of information.

You won't get a "merge updates" behavior out of any of the framework methods like this. If you have an existing version that you want to add to or otherwise update, you'll need to load/have the original version in memory as a mutable dictionary, then make the changes or additions to it, and then save the whole new thing (with -writeToFile: or something else).

If you're adding a bunch of entries in a loop, add all the entries first, then write the dictionary to disk as a file when it's done.

Yes writeToFile will overwrite the previous content,

So you can just read the previous content of your file into NSMutableDictionary and then add new content to this mutableDictionary ,and then write this mutableDictionary(which holds both old and new content) to your file path.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM