ios 5: недопустимое обновление: неверное количество строк в разделе

У меня такие проблемы только с iOS 5, с iOS 6 проблем нет

это мой журнал

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 3.  The number of rows contained in an existing section after the update (3) must be equal to the number of rows contained in that section before the update (1), plus or minus the number of rows inserted or deleted from that section (0 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'

И мой код

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [[dictionary allKeys] count];
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    NSArray *keyArray = [dictionary allKeys];
    return [[dictionary objectForKey:[keyArray objectAtIndex:section]] count];
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
=    if (editingStyle == UITableViewCellEditingStyleDelete)
    {

        //First get all the keys of dictionary into one array
        NSArray *sectionsArray = [dictionary allKeys];
        //Get all the data of tapped section into one array by using indexpath.section
        NSMutableArray *objectsAtSection = [dictionary objectForKey:[sectionsArray objectAtIndex:indexPath.section]];
        //remove the particular object by using indexPath.row from the array
        [objectsAtSection removeObjectAtIndex:indexPath.row];
        // Update dictionary

        [table beginUpdates];

        // Either delete some rows within a section (leaving at least one) or the entire section.
        if ([objectsAtSection count] > 0)
        {
            [dictionary setObject:objectsAtSection forKey:[sectionsArray objectAtIndex:indexPath.section]];
            // Section is not yet empty, so delete only the current row.
            // Delete row using the cool literal version of [NSArray arrayWithObject:indexPath]
            [table deleteRowsAtIndexPaths:@[indexPath]
                             withRowAnimation:UITableViewRowAnimationFade];
        }else{
            [dictionary removeObjectForKey:[sectionsArray objectAtIndex:indexPath.section]];
            // Section is now completely empty, so delete the entire section.
            [table deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section]
                     withRowAnimation:UITableViewRowAnimationFade];
        }
        [table endUpdates];
    }
}

в iOS 5 после удаления некоторых строк и некоторых разделов у меня возникают проблемы.

Не могли бы вы мне помочь?


person Nam Vu    schedule 23.07.2013    source источник
comment
Я думаю, что проблема в [словаре allKeys] у меня нет в (ios 5), allKeys возвращает случайный порядок ключей, просто проверьте, поставив точки останова в этих операторах (я не уверен в этом, просто попробуйте)   -  person Shankar BS    schedule 23.07.2013
comment
но в iOS 5 после удаления некоторых строк и некоторых разделов у меня возникают проблемы.   -  person Nam Vu    schedule 23.07.2013
comment
Просто добавьте [self.tableView reloadData]; и саморедактирование = YES; Это необходимо, потому что табличное представление изначально не имеет информации об источнике данных и делегате; если вы создаете табличное представление, ему всегда нужно отправлять сообщение reloadData как часть его инициализации.   -  person 9to5ios    schedule 23.07.2013
comment
использовать [количество словарей]; везде (не уверен)   -  person Shankar BS    schedule 23.07.2013
comment
Является ли ваш dictionary объектом NSMutableDictionary?   -  person Stas    schedule 23.07.2013
comment
да, NSMutableDictionary   -  person Nam Vu    schedule 23.07.2013


Ответы (2)


Хорошо, кажется, я нашел ответ. См. этот вопрос SO и ответ, объясняющий почему использование метода allKeys плохо.

Пока вы не добавите или не удалите какие-либо элементы из словаря, они останутся в том же порядке, но как только вы добавите или удалите элемент, новый порядок будет совершенно другим.

person Stas    schedule 23.07.2013
comment
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return [количество словарей]; } я пытаюсь использовать это, но ничего не меняется - person Nam Vu; 23.07.2013
comment
заменить NSMutableDictionary на OrderedDictionary - хороший способ. Вы спасаете мою жизнь. Спасибо - person Nam Vu; 23.07.2013

Нужно добавить

[self.tableView reloadData];

и

self.editing = YES;

Это необходимо, потому что табличное представление изначально не имеет информации об источнике данных и делегате; если вы создаете табличное представление, ему всегда нужно отправлять сообщение reloadData как часть его инициализации.

Надеюсь, это поможет вам

person 9to5ios    schedule 23.07.2013
comment
все еще есть эта проблема после удаления 10 разделов - person Nam Vu; 23.07.2013
comment
Также предлагаем вам проверить, правильно ли ваше свойство tableView подключено к UITableView в вашем XIB-файле интерфейса. Выполните NSLog(@%@, self.tableView); в вашем viewWillAppear: также для получения обновленного списка необходимо было еще раз вызвать метод viewdidLoad, помимо reloaddata self.tableView. Надеюсь, это поможет вам - person 9to5ios; 23.07.2013