I’m trying to reorder UITableView in iOS application.
After harvesting a lot of StackOverFlow questions, I used this:
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
self.userDrivenDataModelChange = YES;
NSUInteger fromIndex = fromIndexPath.row;
NSUInteger toIndex = toIndexPath.row;
NSManagedObject *affectedObject = [self.fetchedResultsController.fetchedObjects objectAtIndex:fromIndex];
[affectedObject setValue: [NSNumber numberWithInt:toIndex] forKey:@"priority"];
NSUInteger start, end;
int delta;
if (fromIndex < toIndex) {
// move was down, need to shift up
delta = -1;
start = fromIndex + 1;
end = toIndex;
} else { // fromIndex > toIndex
// move was up, need to shift down
delta = 1;
start = toIndex;
end = fromIndex - 1;
}
for (NSUInteger i = start; i <= end; i++) {
NSManagedObject *otherObject = [self.fetchedResultsController.fetchedObjects objectAtIndex:i];
NSNumber *oldPriority = (NSNumber *)[otherObject valueForKey:@"priority"];
int tmp = [oldPriority intValue] + delta;
NSNumber *newPriority = [NSNumber numberWithInt:tmp];
[otherObject setValue: [NSNumber numberWithInt:[newPriority intValue]] forKey:@"priority"];
}
NSError *error = nil;
if (! [self.fetchedResultsController.managedObjectContext save:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
// Should I call something here?
self.userDrivenDataModelChange = NO;
}
After sending save message to the context object, What should I call? some method on the fetch controller or the table view? because it is not working in the current shape.
Should I send save to the context object in the first place?
You’re already sending save message to managedObjectContext, which is fine,
if (! [self.fetchedResultsController.managedObjectContext save:&error]).To see updated results in table view, it’ll be probably sufficient to call
[tableView reloadData];at the end of this method.