Delete request and sync RESTkit with core data and threading

357 Views Asked by At

To be clear... My objectives :-

1. Make a delete request to server (done), I get response but not sure whether its synced with core data DB or not. therefore, I need to know, how to delete a particular object from db using Restkit.

2. ManagedObjectContext confusion -- I am too confused with context and threads. I am using everywhere for all my operation this context. :- [RKObjectManager sharedManager].managedObjectStore.mainQueueManagedObjectContext] But I want to keep the processing on Bg thread and receive the result on main thread to update. Now there is some concept of child context. How to use it is a puzzle till now for me.

3. If I want to use multithreading, for making server request using Restkit and mapping. How to use managedobjectcontext. (I mean the right way of using it)

1

There are 1 best solutions below

1
On

You can use below code to manage NSManagedObjectContext in multithreaded

- (void)mergeChanges:(NSNotification*)notification
{
    NSLog(@"[mergeChanges] enter");
    // save changes to manageObjectContext on main thread
    AppDelegate *theDelegate = [[UIApplication sharedApplication] delegate];
    [[theDelegate managedObjectContext] performSelectorOnMainThread:@selector(mergeChangesFromContextDidSaveNotification:)
                                                         withObject:notification
                                                      waitUntilDone:YES];
    NSLog(@"[mergeChanges] leave");
}

- (NSManagedObjectContext*)startThreadContext
{
    AppDelegate *theDelegate = [[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *newMoc = [[NSManagedObjectContext alloc] init];
    [newMoc setPersistentStoreCoordinator:[theDelegate persistentStoreCoordinator]];

    // Register for context save changes notification
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(mergeChanges:)
                                                 name:NSManagedObjectContextDidSaveNotification
                                               object:newMoc];

    return newMoc;
}

- (void)stopThreadContext:(NSManagedObjectContext*)context
{
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:NSManagedObjectContextDidSaveNotification
                                                  object:context];
}

At the beginning of the thread context you can call

-(NSManagedObjectContext*)startThreadContext

and use the new NSManagedObjectContext in the thread and you can remove the NSManagedObjectContext when your thread is finished. When ever you save the new NSManagedObjectContext it notify the main thread's managed object context to save the changes.