moveRowAtIndexPath: как удалить раздел после перемещения последней строки в другой раздел - PullRequest
3 голосов
/ 11 октября 2009

У меня есть таблица с несколькими разделами. Я хотел бы иметь возможность перемещать строки из одного раздела в другой и удалять раздел, если в нем нет строк. Я пытаюсь сделать это с помощью 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 ]

3 голосов
/ 31 июля 2012

Мне повезло, выполнив метод deleteSections в блоке после окончания метода moveRowAtIndexPath, обернув удаление в 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];
        }
    });
0 голосов
/ 27 августа 2013

Это также дало мне некоторое горе. Я успешно выполнил удаление раздела с задержкой.

Вот как я заставил его работать - при условии, что вы используете хранилище для хранения всех объектов, а в магазине есть методы для перемещения элементов:

- (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];
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...