In my UITableView I have this said relationship
Department -< Employees
(array of names)
I have set up custom objects for each model.
Your problem is that you have manipulated the data model, but you haven't told the tableview about the changes you made.
Because you call beginUpdates
/endUpdates
the tableview is expecting some changes, so after endUpdates
it calls numberOfRowsInSection
- which returns the answer '3' - but it is expecting 2+0 (because you didn't tell it about the new row).
You have a couple of options:
1 - Use moveRowAtIndexPath:toIndexPath:
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
if (fromIndexPath != toIndexPath ) {
Department *department = [_objects objectAtIndex:fromIndexPath.section];
Employee *employee = [department.employees objectAtIndex:fromIndexPath.row];
[tableView beginUpdates];
[department.employees removeObjectAtIndex:fromIndexPath.row];
[department.employees insertObject:employee atIndex:toIndexPath.row];
[tableview moveRowAtIndexPath:fromIndexPath toIndexPath:toIndexPath];
[self.tableView endUpdates];
}
}
2 - Use reload without the beginUpdate
/endUpdate
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
if (fromIndexPath != toIndexPath ) {
Department *department = [_objects objectAtIndex:fromIndexPath.section];
Employee *employee = [department.employees objectAtIndex:fromIndexPath.row];
[department.employees removeObjectAtIndex:fromIndexPath.row];
[department.employees insertObject:employee atIndex:toIndexPath.row];
[tableView reloadData];
}
}
Thanks to @Paulw11, the solution was that I did not account for the departmentFrom and departmentTo, as what I wanted was to Move Tom from Sales to Marketing
;
Thus the fix I have is:
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
if (fromIndexPath != toIndexPath ) {
Department *departmentFrom = [_objects objectAtIndex:fromIndexPath.section];
Department *departmentTo = [_objects objectAtIndex:toIndexPath.section];
Employee *employee = [departmentFrom.employees objectAtIndex:fromIndexPath.row];
[departmentFrom.employees removeObjectAtIndex:fromIndexPath.row];
[departmentTo.employees insertObject:employee atIndex:toIndexPath.row];
[tableView reloadData];
}
}
Accepted Paulw11 answer.