DAN
DAN

Reputation: 939

RestKit + CoreData: replace entity content in case of operation success, leave as it is in case of failure

I've implemented a simple REST request in a structure as follows:

RKManagedObjectRequestOperation *operation = [[RKManagedObjectRequestOperation alloc] initWithRequest:request responseDescriptors:@[responseDescriptor]];
operation.targetObject = nil;
operation.savesToPersistentStore = YES;
operation.managedObjectContext = [RKManagedObjectStore defaultStore].mainQueueManagedObjectContext;
operation.managedObjectCache = [RKManagedObjectStore defaultStore].managedObjectCache;

[operation setCompletionBlockWithSuccess:^(RKObjectRequestOperation *operation, RKMappingResult *result) {
    // Handle success   
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
    // Handle failure
}];

How can I modify the code so that:

In order to delete the DB entity, before the operation I would do as reported here: Core Data: Quickest way to delete all instances of an entity, but that would empty the entity no matter what the WS answer is.

Any help is really appreciated, Thanks a lot, DAN

EDIT1:

As suggested by @Wain, I've added a fetch request block to the operation like this:

RKFetchRequestBlock fetchRequestBlock = ^NSFetchRequest *(NSURL *URL)
{
    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"EntityToBeUpdated"];
    fetchRequest.sortDescriptors = @[ [NSSortDescriptor sortDescriptorWithKey:@"order" ascending:NO] ];
    return fetchRequest;
};

operation.fetchRequestBlocks = @[fetchRequestBlock];
operation.deletesOrphanedObjects = YES;

but the result doesn't change: the items on db are not updated or deleted.

Upvotes: 0

Views: 532

Answers (1)

Wain
Wain

Reputation: 119031

RestKit is based around updating rather than replacing. As such your requirement is hard to manage during mapping. You could consider:

  1. Have RestKit create a new instance and delete the old one in the success block - duplicate objects for a short time.
  2. Use a dynamic mapping to check the response before mapping is started to decide wether to delete or not - kinda hacky.
  3. Have the JSON response contain values for all keys so everything will be overwritten.

From an error point of view, if the error is returned with an HTTP status code and you have no response descriptor for that code then RestKit will change nothing.


Based on your comment below, you are actually looking for orphaned item deletion. This is done using fetch request blocks. See section Fetch Request Blocks and Deleting Orphaned Objects here. You don't need a predicate, just a fetch request.

Upvotes: 1

Related Questions