I'm using RestKit 0.2 to get a JSON file from my server and map the objects to my CoreData stack (analog to the TwitterCoreData example).
In the first request, I get the following result: Artist1, Artist2, Artist3
.
In the second request, one artist is outdated and the result looks like this: Artist1, Artist3
.
Now the Artist2
should be deleted from my local store and disappear in my UITableView
. However, I can't find a way to delete the Artist2
from my local storage.
How do I delete an object in RestKit 0.2 from a managed object store?
This is what I am doing:
#pragma mark - Data methods
- (void)fetchResults {
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Artists"];
NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@"ordernr" ascending:YES];
fetchRequest.sortDescriptors = @[descriptor];
NSError *error = nil;
// Setup fetched results
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:[RKManagedObjectStore defaultStore].mainQueueManagedObjectContext
sectionNameKeyPath:nil
cacheName:nil];
[self.fetchedResultsController setDelegate:self];
BOOL fetchSuccessful = [self.fetchedResultsController performFetch:&error];
if(fetchSuccessful){
data = [self.fetchedResultsController fetchedObjects];
[_tableView reloadData];
NSLog(@"Fetched artists: %i", [[self.fetchedResultsController fetchedObjects] count]);
}
}
- (void)loadData {
[[RKObjectManager sharedManager] getObjectsAtPath:@"/artists.php" parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
NSLog(@"Fetched artists: %i", [[mappingResult array] count]);
for (id object in data) {
if (NO == [[mappingResult array] containsObject:object]){
NSLog(@"DELETE 1 object...");
//HOW TO DELETE THE OBJECT HERE??
}
}
[[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"ArtistsLastUpdatedAt"];
[[NSUserDefaults standardUserDefaults] synchronize];
[self fetchResults];
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
RKLogError(@"Load failed with error: %@", error);
}];
}
Try the following:
NSManagedObjectContext *context = object.managedObjectContext;
[context deleteObject:object];
NSError *error;
if (![context save:&error]) {
NSLog(@"delete error");
// Handle the error, update UI etc.
}