Search code examples
ioscachingnetwork-programmingrestkitrestkit-0.20

What's the best way to implement caching behavior for the app using RestKit


I need a help in determining the most appropriate and convenient way to implement caching in my app, so that it would provide the behavior described below.

The app needs to display a list of objects A. It displays objects from cache, while simultaneously requesting the updated version of the list from server. If request is successful, cached objects are completely replaced by the returned ones. The list presented to the user is then refreshed.

Right now I'm achieving this behavior by having a dedicated singleton of a class called DataManager, which incapsulates one instance of ApiClient (that sends requests to server) and one instance of CacheProvider (which is basically a set of convenient methods for accessing Core Data objects). Each method in DataManager looks something like this:

- (NSArray *)objectsAWithUpdatedBlock:(void (^)(NSArray *updatedObjects))updatedBlock
{
    [_apiClient requestObjectsAWithCompletionBlock:^(NSArray *objects, NSError *error) {
        if (error == nil) {
            [_cacheProvider replaceCachedObjectsAWithObjects:objects];
            updatedBlock([_cacheProvider cachedObjectsA]);
        }
    }];

    return [_cacheProvider cachedObjectsA];
}

But I have a feeling that I am reinventing the wheel and there must be some standard ways to get the same behavior with RestKit. Am I right or should I continue using my approach?


Solution

  • I'd use an NSFetchedResultsController to get the results to display. It doesn't care if they're cached or not, it just uses what is in the data store and observes changes there (so you don't need your own callback blocks).

    RestKit offers a feature called fetch request blocks, which isn't a great name necessarily, but you use it to delete orphaned objects from the data store - i.e. all of your old cached objects.

    Using these 2 approaches will likely massively reduce the amount of custom code you need to write.