我在一个相当大的 IOS 项目中使用 Magical Record。我使用配置将大型种子数据库与用户数据分开。由于 Magical Record 不支持配置,我解构了 Magical Record 的 setupCoreDataStackWithAutoMigratingSqliteStoreNamed 方法并将其替换为以下内容:
+(void) RB_setupMultipleStores:(NSString *) seedStoreName userStore:(NSString *) userStoreName
/* change persistent store to one with multiple configurations. Assumes Magical Record is initialized to perform auto migration. */
{
NSError * error= nil;
[MagicalRecord cleanUp]; //Tear down Magical Record
NSManagedObjectModel * model = [NSManagedObjectModel MR_defaultManagedObjectModel];
NSURL *seedURL = [NSPersistentStore MR_urlForStoreName:[seedStoreName stringByAppendingString:@".sqlite"]];
NSPersistentStoreCoordinator * coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,
nil];
NSPersistentStore * seedStore =[coordinator
addPersistentStoreWithType:NSSQLiteStoreType
configuration:@"Seed"
URL:seedURL
options:options
error:&error];
if (!seedStore || error)
{
NSLog(@"Error setting up seed store:%@ for %@", [error localizedDescription], seedURL);
exit(-1);
}
NSURL *userURL = [NSURL URLForDocumentDirectoryWithAppendedPath:[userStoreName stringByAppendingString:@".sqlite"]];
NSPersistentStore * userStore = [coordinator
addPersistentStoreWithType:NSSQLiteStoreType
configuration:@"User"
URL:userURL
options:options
error:&error];
if (!userStore || error)
{
NSLog(@"Error setting up user store:%@ for %@", [error localizedDescription], userURL);
exit (-1);
}
[NSPersistentStoreCoordinator MR_setDefaultStoreCoordinator:coordinator];
//Bring back Magical Record with updated coordinator.
[NSManagedObjectContext MR_initializeDefaultContextWithCoordinator:coordinator];
[[NSManagedObjectContext MR_defaultContext] setUndoManager:nil];
}
现在我将把 Restkit 添加到组合中。我需要共享对象模型和持久存储,而且我宁愿使用一组上下文,也不愿使用两个不同的堆栈。
我看到了五种可能的方法:
修改https://github.com/blakewatters/RKMagicalRecord支持多种配置。这看起来微不足道,但它需要我使用类别来显示一些私有(private)方法,优秀的 MR 开发人员建议不要显式设置 MR 默认和根保存上下文。
首先创建 Magical Record 上下文,然后将它们分配给 Restkit。这会起作用吗?这完全有意义吗?
从同一个 NSPersistentStoreCoordinator 初始化 Restkit 和 Magical Record。这有意义吗?
使用不同但相似的 NSPersistentStoreCoordinators 创建两个独立的堆栈。
创建我自己的堆栈和上下文,并使用这些上下文对 Restkit 和 MR 进行所有调用。
任何人都可以推荐这些或任何其他方法吗?每一个都需要付出巨大的努力才能进行测试。我即将前往 #1 路径。
谢谢...
最佳答案
从根本上说,CoreData 已经有办法处理这个问题。您可以让多个协调员指向同一家商店,或者任何您的场景。每个框架都允许您针对框架本身未创建或设置的堆栈使用。
MagicalRecord 归结为一组用于获取和保存的辅助方法。您不需要使用 MagicalRecord 的任何设置方法来在您的抓取上发挥它的魔力。设置方法可以帮助您更快地开展新项目,并为您在主线程/队列上执行提取时使用的“默认”上下文提供单一访问点。对于所有其他用途,每次都使用明确的 inContext: 参数。使用该参数,您可以使用任何您想要的 MOC,一切都会起作用。这是设计使然。 MagicalRecord 从未被编写来取代 CoreData。编写它是为了使简单的任务更容易。
这样,您可以只让 RestKit 处理您的整个 CoreData 堆栈,并仅将 MagicalRecord 用于获取和保存的便利 API。这将使您不必执行任何这些解决方案,而只需回过头来解决您的应用程序特定问题...
关于ios - 神奇的记录,多种配置和Restkit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24703050/