moveRowAtIndexPath:一旦最后一行移动到另一个部分,如何删除部分

时间:2009-10-11 01:58:52

标签: ios iphone tableview

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

2 个答案:

答案 0 :(得分:3)

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

    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];
        }
    });

答案 1 :(得分: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];
}