Skip to content

Instantly share code, notes, and snippets.

@joekr
Created January 18, 2012 15:41
Show Gist options
  • Save joekr/1633594 to your computer and use it in GitHub Desktop.
Save joekr/1633594 to your computer and use it in GitHub Desktop.
NSFetchedResultsController didChangeObject is using wrong indexPath after sorting
- (void)sortShortListUsingSelectedSortIndex{
NSManagedObjectContext *context = [[AppDelegateiPad ad] managedObjectContext];
NSFetchRequest *shortListRequest = [[NSFetchRequest alloc] init];
[shortListRequest setEntity:[NSEntityDescription entityForName:@"Hip" inManagedObjectContext:context]];
[shortListRequest setPredicate:[NSPredicate predicateWithFormat:@"%@ IN shortLists", self.shortList]];
[NSFetchedResultsController deleteCacheWithName:nil];
if(selectedSortIndex == 0){
[shortListRequest setSortDescriptors:[NSArray arrayWithObjects:[NSSortDescriptor sortDescriptorWithKey:@"number" ascending:YES], nil]];
}else{
[shortListRequest setSortDescriptors:[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES],nil]];
}
fetchRequestController = [[NSFetchedResultsController alloc] initWithFetchRequest:shortListRequest
managedObjectContext:context
sectionNameKeyPath:nil
cacheName:nil];
[shortListRequest release];
fetchRequestController.delegate = self;
NSError *error;
[fetchRequestController performFetch:&error];
[tableView reloadData];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
CustomTableViewCell *cell = (CustomTableViewCell*)[hipsTableView dequeueReusableCellWithIdentifier:[ShortListHipTableViewCell reuseIdentifier]];
if (!cell)
cell = [CustomTableViewCell cell];
Hip *hip = (Hip *)[fetchRequestController objectAtIndexPath:indexPath];
[cell setSelectionStyle:UITableViewCellSelectionStyleBlue];
[cell setShowsReorderControl:NO];
cell.hipNumberLabel.text = [NSString stringWithFormat:@"%d",hip.hipDisplay];
return cell;
}
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
[tableView beginUpdates];
}
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
newIndexPath:(NSIndexPath *)newIndexPath {
switch(type) {
case NSFetchedResultsChangeInsert:
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]
withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeUpdate:
break;
case NSFetchedResultsChangeMove:
break;
}
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
[tableView endUpdates];
[[self.toolbarItems objectAtIndex:0] setEnabled:([[fetchRequestController fetchedObjects] count] > 0)];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment