Ошибка при удалении раздела из моего UITableView - PullRequest
3 голосов
/ 13 января 2012

Мне нужна ваша помощь :(

Я работаю над приложением для iOS, в котором мне пришлось удалить некоторые строки и разделы в UItableView.

Я на Xcode 4.

Я связываю свой tableView с NSarray и словарем, как это:

NSMutableArray *arrTemp1 = [[NSMutableArray alloc]
                         initWithObjects:@"Chris",nil];

    NSMutableArray *arrTemp2 = [[NSMutableArray alloc]
                         initWithObjects:@"Bianca",nil];

    NSMutableArray *arrTemp3 = [[NSMutableArray alloc]
                         initWithObjects:@"Candice",@"Clint",@"Chris",nil];

    NSMutableArray *arrTemp4 = [[NSMutableArray alloc]
                                initWithObjects:@"Candice",@"Clint",@"Chris",nil];

    NSMutableArray *arrTemp5 = [[NSMutableArray alloc]
                                initWithObjects:@"Candice",@"Clint",@"Chris",nil];

    NSMutableArray *arrTemp6 = [[NSMutableArray alloc]
                                initWithObjects:@"Candice",@"Clint",@"Chris",nil];

    NSMutableDictionary *temp = [[NSMutableDictionary alloc]
                         initWithObjectsAndKeys:arrTemp1,@"A",arrTemp2,
                                 @"B",arrTemp3,@"C",arrTemp4, @"D", arrTemp5, @"E", arrTemp6, @"J",nil];
    self.tableContents = temp;
    self.sortedKeys =[[self.tableContents allKeys]
                      sortedArrayUsingSelector:@selector(compare:)];

Когда мне нужно удалить строки или раздел, я использую этот код ->

(void)tableView:(UITableView *)tableView 
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle 
forRowAtIndexPath:(NSIndexPath *)indexPath 
{

    if (editingStyle == UITableViewCellEditingStyleDelete)
    {   
        NSMutableArray *listData = [self.tableContents objectForKey:
                            [self.sortedKeys objectAtIndex:[indexPath section]]];
        NSUInteger row = [indexPath row];

        [listData removeObjectAtIndex:row];

        [tableView beginUpdates];


        if ([listData count] > 0)
        {
            // Section is not yet empty, so delete only the current row.
            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
                             withRowAnimation:UITableViewRowAnimationFade];
        }
        else
        {
            // Section is now completely empty, so delete the entire section.
            [tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] 
                     withRowAnimation:UITableViewRowAnimationFade];
        }

       [tableView endUpdates];
    }
}

Когда я удаляю строки, это работает хорошо .. Когда я удаляю разделы, я получаю следующую ошибку: "* Ошибка подтверждения в - [UITableView _endCellAnimationsWithContext:], /SourceCache/UIKit/UIKit-1912.3/UITableView.m:1030 2012-01-13 16: 42: 45.261 * Завершение работы приложения из-за необработанного исключения «NSInternalInconsistencyException», причина: «Неверное обновление: недопустимое количество разделов. Количество разделов, содержащихся в табличном представлении после обновления (6), должно быть равно количеству разделов, содержащихся в табличном представлении до обновления (6), плюс или минус количество вставленных или удаленных разделов (0 вставлено, 1 Исключено). "

 (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [tableContents count]; // tableContent is a NSMUtableDictionnary*
}

- (NSInteger)tableView:(UITableView *)table
 numberOfRowsInSection:(NSInteger)section 
{
    NSArray *listData =[self.tableContents objectForKey:
                        [self.sortedKeys objectAtIndex:section]];
    return [listData count];
}

Я схожу с ума и захожу на stackOverflow, чтобы попросить о помощи ...

(Извините за мой плохой английский :()

Спасибо всем, кто читает и отвечает !!

Ответы [ 2 ]

2 голосов
/ 13 января 2012

Похоже, что вы на самом деле не удаляете ключ словаря для пустого массива, когда он не содержит объектов, поэтому ваш вызов

        // Section is now completely empty, so delete the entire section.
        [tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] 
                 withRowAnimation:UITableViewRowAnimationFade];

вызывает проблему, поскольку у вас все еще остается то же числоразделы (словарные ключи) как и прежде ...

1 голос
/ 13 января 2012

Попробуйте поменять эти две строки:

[listData removeObjectAtIndex:row];

[tableView beginUpdates];

Так и должно быть:

[tableView beginUpdates];

[listData removeObjectAtIndex:row];
...