iOS: Appending to an archive
Can anyone recommend a memory-efficient way to append data to an archive using NSKeyArchiver?
I have an array which collects objects and makes them available to the app as an in-memory cache. In order to avoid eating more and more memory, I'd like to archive this array to a file every so often, keeping a single cache file (as opposed to creating separate ones).
One way to do this would be to unarchive the exiting file to a tempArray, than add the items in the existing array to it:
[tempArray addObjectsFromArray:array];
and then archive array:
[NSKeyedArchiver archiveRootObject:tempArray toFile:file];
This approach kind of beats its own purpose, because you have to read the entire archive to memory before you archive the new data.
Anyone can recommend a开发者_StackOverflow社区 more elegant solution?
I don't think this is possible, at least with NSKeyedArchiver. Since the keys must be unique within each scope hierarchy, it would be impossible to guarantee that without reading the archive in first. The result would be a corrupt archive if you just inserted a node with a new archived object, and the key for that node already existed earlier in the archive.
Obviously, if you wrote your own implementation of the NSCoder protocol you could make it work however you like. Writing a NSCoder is non-trival however.
精彩评论