问题描述
假设我的应用程序文档目录中有两个 SQLite 文件.我将如何将两者组合在一起并将它们保存为包含两者所有信息的单个文件?我真的必须创建两个持久存储协调器并手动协调两者之间的过程,还是有更有效的方法?
Say I have two SQLite files in my application documents directory. How would I go about combining the two together and saving them as a single file that contained all the information from both? Do I literally have to create two persistent store coordinators and manually coordinate the process between the two, or is there some more efficient way of doing it?
-灰
推荐答案
你的问题不是你需要问的.Core Data 中的 SQLite 存储仅仅是 Core Data 对象图的后备存储.它是一个 SQLite 数据库这一事实对 Core Data 来说并不重要.所以你的问题实际上是,我如何将两个 Core Data 对象图合并为一个?"
Your question isn't quite what you need to ask. A SQLite store in Core Data is merely the backing store for a Core Data object graph. The fact that it's a SQLite database is immaterial to Core Data. So your question is really, "how do I merge two Core Data object graphs into one?"
这在某种程度上取决于您要对数据做什么.Core Data 中的一条规则是,您不能在不同持久存储中的两个对象之间建立关系.因此,如果您不需要存储 A 中的对象和存储 B 中的对象之间的关系,那真的很简单.只需将两个持久存储添加到您的 NSPersistentStoreCoordinator
,两个存储中的所有对象都可以从与该持久存储协调器关联的任何托管对象上下文中获得.
It kind of depends on what you want to do with the data. One of the rules in Core Data is that you can't have relationships between two objects in different persistent stores. So, if you don't have a need for relationships between objects in Store A and objects in Store B, it's really quite simple. Just add both persistent stores to your NSPersistentStoreCoordinator
, and all the objects from both stores will be available from any managed object context associated with that persistent store coordinator.
如果您确实需要在两个商店中的对象之间建立关系,或者您真的只想拥有一个商店,那么最好的办法是创建第二个 NSPersistentStoreCoordinator
和第三个不同的持久存储来保存合并的对象图.您将需要编写代码以在附加到第二个 NSPersistentStoreCoordinator
的托管对象上下文中创建对象的副本.您还需要在原始对象所具有的副本之间建立相同的关系,但是如何执行此操作取决于您的数据模型.如果您想为您的问题添加更多细节,也许我可以让您更好地了解所涉及的内容.
If you do need to have relationships between the objects in both stores, or you really just want to have a single store, your best bet would be to create a second NSPersistentStoreCoordinator
and a third, distinct persistent store to hold the merged object graph. You will need to write code to create copies of the objects in a managed object context attached to this second NSPersistentStoreCoordinator
. You'll need to set up the same relationships among the copies that the original objects had, too, but how you go about doing this depends on your data model. If you want to add some more detail to your question, maybe I can give you a better idea of what would be involved.
这篇关于将两个 SQLite 存储合并为一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!