我有一个包含几个部分的表格视图。我希望能够将行从一个部分移动到另一个部分,并在没有行时删除一个部分。我正在尝试通过 moveRowAtIndexPath 执行此操作,但我拥有的代码不起作用并引发 NSRangeException 异常。
这是一个代码示例:
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
NSUInteger fromSection = [fromIndexPath section];
NSUInteger fromRow = [fromIndexPath row];
NSString *fromKey = [self.keys objectAtIndex:fromSection];
NSMutableArray *fromEventSection = [self.eventsDict objectForKey:fromKey];
NSUInteger toSection = [toIndexPath section];
NSUInteger toRow = [toIndexPath row];
NSString *toKey = [self.keys objectAtIndex:toSection];
NSMutableArray *toEventSection = [self.eventsDict objectForKey:toKey];
id object = [[fromEventSection objectAtIndex:fromRow] retain];
[fromEventSection removeObjectAtIndex:fromRow];
[toEventSection insertObject:object atIndex:toRow];
[object release];
// The above code works just fine!
// Try to delete an empty section. Here is where trouble begins:
if ((fromSection != toSection) && [fromEventSection count] == 0) {
[self.keys removeObjectAtIndex:fromSection];
[self.eventsDict removeObjectForKey:fromKey];
[tableView deleteSections:[NSIndexSet indexSetWithIndex:fromSection] withRowAnimation:UITableViewRowAnimationFade];
}