4

我有一个包含几个部分的表格视图。我希望能够将行从一个部分移动到另一个部分,并在没有行时删除一个部分。我正在尝试通过 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];
    }
4

2 回答 2

3

通过将删除包装在 dispatch_async 中,我很幸运地在 moveRowAtIndexPath 方法结束后的块中执行了 deleteSections 方法。

    dispatch_async(dispatch_get_main_queue(), ^{
        if ((fromSection != toSection) && [fromEventSection count] == 0) {
            [self.keys removeObjectAtIndex:fromSection];
            [self.eventsDict removeObjectForKey:fromKey];
            [tableView deleteSections:[NSIndexSet indexSetWithIndex:fromSection] withRowAnimation:UITableViewRowAnimationFade];
        }
    });
于 2012-07-31T14:37:10.713 回答
0

这也让我有些心酸。我已经成功使用延迟执行部分删除。

这是我如何让它工作的——假设您使用商店来包含所有对象,并且商店有移动项目的方法:

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
    NSInteger beforeSectionCount = [store sectionCount];
    [store moveObject:fromIndexPath toIndexPath:toIndexPath];
    if (beforeSectionCount > [store sectionCount]
        [self performSelector:@selector(deleteSection:) withObject:fromIndexPath: afterDelay:0.2]
}

- (void)deleteSection:(NSIndexPath *)indexPath {
    [[self tableView] beginUpdates];
    [[self tableView] deleteSections:[NSIndexSet indexSetWithIndex:[indexPath section]]
                withRowAnimation:UITableViewRowAnimationFade];
    [[self tableView] endUpdates];
}
于 2013-08-27T01:27:44.470 回答