gpt4 book ai didi

ios - NSPersistentStoreCoordinator 有两种类型的持久存储?

转载 作者:技术小花猫 更新时间:2023-10-29 11:03:37 25 4
gpt4 key购买 nike

在 iOS 应用程序中,我想将 NSPersistentStoreCoordinatorNSIncrementalStore 子类一起使用,用于从 REST API 获取数据,但也与 SQLite 存储一起使用,保存到磁盘。但是,如果我将这两种类型的持久存储添加到我的协调器中,则在我的托管对象上下文中调用 save: 没有任何效果。如果我只添加一个持久存储,而不是我的 NSIcrementalStore 子类的类型,那么保存会按预期工作。

有什么办法可以实现这个功能吗?

最佳答案

根据我的经验,最好的解决方案是拥有多个托管对象上下文,每个上下文都有自己的模型。

但是,有一种方法可以完成您想要的:

// create the store coordinator
NSPersistentStoreCoordinator *storeCoordinator = [[NSPersistentStoreCoordinator alloc] init];
// create the first store
NSPersistentStore *firstStore = [storeCoordinator addPersistentStoreWithType: NSIncrementalStore configuration:nil URL:urlToFirstStore options:optionsForFirstStore error:&error];
// now create the second one
NSPersistentStore *secondStore = [storeCoordinator addPersistentStoreWithType:NSSQLiteStore configuration:nil URL:urlToSecondStore options:optionsForSecondStore error:&error];

// Now you have two stores and one context
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
[context setPersistentStoreCoordinator:storeCoordinator];

// and you can assign your entities to different stores like this
NSManagedObject *someObject = [[NSManagedObject alloc] initWithEntity:someEntity insertIntoManagedObjectContext:context];
// here the relevant part
[context assignObject:someObject toPersistentStore:firstStore]; // or secondStore ..

您还应该检查这些链接以更好地了解 Core Data 的工作原理:

Core Data Programming Guide - Persistent Store Coordinator

SO: Two persistent stores for one managed object context - possible?

SO: Can two managed object context share one single persistent store coordinator?

另请查看 TechZen 在第二个链接中关于配置的评论,并在此处阅读:

Core Data Programming Guide - Configurations

这里有一个很好的教程来管理两个对象上下文:

Multiple Managed Object Contexts with Core Data

关于ios - NSPersistentStoreCoordinator 有两种类型的持久存储?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12321954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com