我想继续使用我当前的RestKit,同时使用MagicRecord进行其余的提取和更新。我希望Restkit的MOC发送更新到MagicRecord的默认上下文。如果我理解正确,这就是我在做的事情。这可以吗?
NSManagedObjectContext* context = [[RKObjectManager sharedManager].objectStore managedObjectContextForCurrentThread];
[MagicalRecord setupCoreDataStackWithAutoMigratingSqliteStoreNamed:[XDBStore storeName]];
[context setParentContext:[NSManagedObjectContext MR_defaultContext]];
也许是另一种方法,但仍然不确定。
NSPersistentStoreCoordinator *coordinator = [[[RKObjectManager sharedManager] objectStore] persistentStoreCoordinator];
[NSPersistentStoreCoordinator MR_setDefaultStoreCoordinator:coordinator];
[NSManagedObjectContext MR_initializeDefaultContextWithCoordinator:coordinator];
以前有人遇到过同样的问题吗?
编辑1
我尝试了@ casademora的建议#1来设置默认上下文,但是出现了这个错误。
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Can only use -performBlockAndWait: on an NSManagedObjectContext that was created with a queue.'
编辑2
我找到了一个黑客。首先,在magicalrecord中打开默认上下文的setter。接下来,更改RestKit存储的并发类型,以便可以在magicalrecord中使用其上下文。
的NSManagedObjectContext + MagicalRecord.h
+ (void) MR_setDefaultContext:(NSManagedObjectContext *)moc;
+ (void) MR_setRootSavingContext:(NSManagedObjectContext *)context;
RKManagedObjectStore.m
NSManagedObjectContext *managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
然后像这样设置MagicalRecord:
NSManagedObjectContext* context = [[RKObjectManager sharedManager].objectStore managedObjectContextForCurrentThread];
[NSManagedObjectContext MR_setRootSavingContext:context];
NSManagedObjectContext *defaultContext = [NSManagedObjectContext MR_newMainQueueContext];
[defaultContext setParentContext:context];
[NSManagedObjectContext MR_setDefaultContext:defaultContext];
答案 0 :(得分:7)
有一个示例项目可用于展示如何将RestKit与MagicalRecord @ https://github.com/blakewatters/RKMagicalRecord一起使用
答案 1 :(得分:1)
总结Blake的解决方案
使用类扩展来公开对MagicalRecord私有setter方法的访问
@interface NSManagedObjectContext ()
+ (void)MR_setRootSavingContext:(NSManagedObjectContext *)context;
+ (void)MR_setDefaultContext:(NSManagedObjectContext *)moc;
@end
先进行核心数据设置,然后再进行
[NSPersistentStoreCoordinator MR_setDefaultStoreCoordinator:managedObjectStore.persistentStoreCoordinator];
[NSManagedObjectContext MR_setRootSavingContext:managedObjectStore.persistentStoreManagedObjectContext];
[NSManagedObjectContext MR_setDefaultContext:managedObjectStore.mainQueueManagedObjectContext];
答案 2 :(得分:0)
有两种方法可以实现这一目标:
1)从RestKit获取主上下文,并将其设置为默认上下文:
NSManagedObjectContext *rkContext = ...; //You'll have to figure this part out
[NSManagedObjectContext MR_setDefaultContext:rkContext];
2)对于你所做的每次获取,只需指定上下文:
NSMangedObjectContext *rkContext = ...; //again, I don't know where to get this in restkit
[MyEntity MR_findAllInContext:rkContext]; // <- This will use the RestKit context