NSCry
NSCry

Reputation: 1652

Cache Webservice data into core data

What's the good way to accompolish caching of web service data into core data.Main objective is to sync web service data into core data when device will be online or some update will be happened and user able to get the data in offline also.So how that thing will be implemented any good suggestions.

Upvotes: 0

Views: 773

Answers (2)

LJ Wilson
LJ Wilson

Reputation: 14427

I have done this. My process was to use a network client (in my case, AFNetworking), and then upon a successful request, I would do the following:

Remove all objects from the Core Data Entity

Create an NSOperationQueue in the AppDelegate and use a custom Parser class that instantiated a new ManagedObjectContext to be used on the background thread

Parse the response from the web service and insert the objects back into the CD Entity on a background thread using

// Register context with the notification center
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; 
[nc addObserver:self
       selector:@selector(mergeChanges:) 
           name:NSManagedObjectContextDidSaveNotification
          object:ctx];

Then when I saved the managed object (I did a save every five passes), the notification would get sent and this method would get fired:

- (void)mergeChanges:(NSNotification *)notification
{
    id appDelegate = [[UIApplication sharedApplication] delegate];

    NSManagedObjectContext *mainContext = [appDelegate managedObjectContext];

    // Merge changes into the main context on the main thread
    [mainContext performSelectorOnMainThread:@selector(mergeChangesFromContextDidSaveNotification:) 
                              withObject:notification
                           waitUntilDone:NO];
}

This would update the Core Data Entity mostly in the background and then merge the changes (every five "records") in the main thread. My initial UI for the user was a TableView that relied on the Core Data Entity being updated and the update was plenty fast enough for the user to be able to use the tableview while new data was coming in (the FetchedResultsController would manage the inserting of new rows in the TV).

I can send more code if needed, but the gist of it was to parse the created the managed objects on a background thread using NSOperationQueue and then merge the changes to the context every so often (in my case 5 records) using the main thread's MOC.

Upvotes: 2

Max B.
Max B.

Reputation: 871

Try RestKit: http://restkit.org/

RestKit's primary goal is to allow the developer to think more in terms of their application's data model and worry less about the details of sending requests, parsing responses, and building representations of remote resources.

Upvotes: 1

Related Questions