Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use MagicalRecord with another existing context in RestKit

I want to keep using my current RestKit while use MagicRecord for rest of fetches and updates. I want Restkit's MOC send updates to MagicRecord's default context. If I understand right, this is what I am doing. Is this ok?

NSManagedObjectContext* context = [[RKObjectManager sharedManager].objectStore managedObjectContextForCurrentThread];
[MagicalRecord setupCoreDataStackWithAutoMigratingSqliteStoreNamed:[XDBStore storeName]];
[context setParentContext:[NSManagedObjectContext MR_defaultContext]];

Maybe another way to do it, but still not sure.

NSPersistentStoreCoordinator *coordinator = [[[RKObjectManager sharedManager] objectStore] persistentStoreCoordinator]; 
[NSPersistentStoreCoordinator MR_setDefaultStoreCoordinator:coordinator]; 
[NSManagedObjectContext MR_initializeDefaultContextWithCoordinator:coordinator];

Anyone had same issue before?

EDIT 1

I tried the @casademora's suggestion #1 to set default context, but got this error.

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Can only use -performBlockAndWait: on an NSManagedObjectContext that was created with a queue.'

EDIT 2

I found a hack. First, open up the setter for default context at magicalrecord. Next, change the concurrency type for RestKit store so its context can be used at magicalrecord.

NSManagedObjectContext+MagicalRecord.h

+ (void) MR_setDefaultContext:(NSManagedObjectContext *)moc;
+ (void) MR_setRootSavingContext:(NSManagedObjectContext *)context;

RKManagedObjectStore.m

NSManagedObjectContext *managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];

Then setup MagicalRecord like this:

NSManagedObjectContext* context = [[RKObjectManager sharedManager].objectStore managedObjectContextForCurrentThread];
[NSManagedObjectContext MR_setRootSavingContext:context];

NSManagedObjectContext *defaultContext = [NSManagedObjectContext MR_newMainQueueContext];
[defaultContext setParentContext:context];
[NSManagedObjectContext MR_setDefaultContext:defaultContext];
like image 242
angelokh Avatar asked Dec 10 '25 20:12

angelokh


1 Answers

There is an example project available showcasing how to use RestKit with MagicalRecord @ https://github.com/blakewatters/RKMagicalRecord

like image 60
Blake Watters Avatar answered Dec 12 '25 13:12

Blake Watters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!