iOS:追加到存档
任何人都可以推荐一种使用 NSKeyArchiver 将数据附加到存档的内存高效方法吗?
我有一个数组,它收集对象并使它们作为内存缓存可供应用程序使用。为了避免消耗越来越多的内存,我想经常将此数组存档到文件中,保留单个缓存文件(而不是创建单独的缓存文件)。
执行此操作的一种方法是将现有文件解档到 tempArray,然后将现有数组中的项目添加到其中:
[tempArray addObjectsFromArray:数组];
然后归档数组:
[NSKeyedArchiver archiveRootObject:tempArray toFile:file];
这种方法有点违背了它自己的目的,因为在归档新数据之前,您必须将整个归档读取到内存中。
任何人都可以推荐一个更优雅的解决方案吗?
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 more elegant solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为这是不可能的,至少对于 NSKeyedArchiver 来说是这样。由于键 必须是唯一的 在每个作用域层次结构中,如果不首先读取存档,就不可能保证这一点。如果您刚刚插入带有新归档对象的节点,并且该节点的密钥先前已存在于归档中,则结果将是损坏的归档。
显然,如果您编写了自己的 NSCoder 协议实现,您可以让它按照您喜欢的方式工作。然而,编写 NSCoder 并不简单。
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.