NSInternalInconsistencyException при удалении / вставке строк в UITableView - PullRequest
2 голосов
/ 17 октября 2011


Мне нужно создать приложение с tableView.Сейчас я могу просто загрузить / перезагрузить все данные в моей таблице.Для добавления / удаления операции tableView имеет режим редактирования.Но проблема в том, что в этом режиме tableView показывает стандартные кнопки добавления / удаления.Но мне не нужны эти кнопки.В руководстве Apple я нашел другой способ добавить / удалить строку, например:

[data removeObjectAtIndex:0];
[data addObject:[[chooseTypeCell alloc]init]];
NSIndexPath *insertIndexPaths=[NSIndexPath indexPathForRow:[data count] inSection:0]; 
NSIndexPath *deleteIndexPaths=[NSIndexPath indexPathForRow:0 inSection:0];
[[self view] beginUpdates];
[[self view] insertRowsAtIndexPaths:[NSArray arrayWithObject:insertIndexPaths] withRowAnimation:UITableViewRowAnimationRight];
[[self view] deleteRowsAtIndexPaths:[NSArray arrayWithObject:deleteIndexPaths] withRowAnimation:UITableViewRowAnimationFade];
[[self view] endUpdates];

Но это вызывает ошибку = (.

Завершение работы приложения из-за невыполненияисключение «NSInternalInconsistencyException», причина: «Неправильное обновление табличного представления. Приложение запросило обновление табличного представления, которое не соответствует состоянию, предоставленному источником данных.»

В моем случае I 'используя объект, который является подклассом UITableViewController, с протоколами UITableViewdataSource и UITableViewDelegate. В этом объекте переменная представления связана с моим UITableView. В результате UITableView соединяется только с его контроллером. В этом контроллере я определил эти методы:

#pragma mark - Table view data source

#######>>>>> right code =)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

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

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


#######>>>>> in comment section

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath

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

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath
toIndexPath:(NSIndexPath *)toIndexPath

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath

#######>>>>> without any code or cap

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath
toIndexPath:(NSIndexPath *)toIndexPath

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView

#pragma mark - Table view delegate

#######>>>>> right code =)

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath  
#######>>>>> in comment section

 - (NSIndexPath *)tableView:(UITableView *)tableView willDeselectRowAtIndexPath:(NSIndexPath *)indexPath 

 - (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath

#######>>>>> without any code or cap

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath
*)indexPath

- (void)tableView:(UITableView *)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath
*)indexPath

- (NSIndexPath *)tableView:(UITableView *)tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath
*)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath

- (BOOL)tableView:(UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath

- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath

- (void)tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

Есть идеи, что не так?

1 Ответ

8 голосов
/ 19 октября 2011

Ошибка как это:

Ошибка подтверждения в - [_ UITableViewUpdateSupport _computeRowUpdates], /SourceCache/UIKit/UIKit-1912.3/UITableViewSupport.m:386 Завершение работы приложения из-за необработанного исключения «NSInternalInconsistencyException», причина: «Недопустимое табличное представление Обновить. Приложение запросило обновление представления таблицы. это не согласуется с состоянием, предоставленным источником данных. '

Может появиться, потому что ваш класс UITable-Data определен неправильно. Вам необходимо обратить внимание на следующие методы:

- (NSInteger) numberOfSectionsInTableView: (UITableView *) tableView
- (UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath
- (NSInteger) tableView: (UITableView *) tableView numberOfRowsInSection: (NSInteger) раздел

Также вам необходимо проверить код анимации. Все индексы должны быть взяты из структура данных результата .

В документации Apple:

Укажите операции удаления и перезагрузки внутри блока анимации. какие строки и разделы в исходной таблице следует удалить или перезагружается; вставки указывают, какие строки и разделы должны быть добавлены к итоговой таблице. Индексные пути, используемые для идентификации разделов и строки следуют этой модели. Вставка или удаление элемента в изменяемом массив, с другой стороны, может влиять на индекс массива, используемый для последовательная операция вставки или удаления; например, если вы вставите элемент по определенному индексу, индексы всех последующих элементов в массив увеличивается.

В моем случае: ошибка возникает в функции insertRowsAtIndexPaths . Потому что все мои изменения (в моих данных) были применены ко времени исполнения. И новая позиция моего UITableViewCell была ([количество данных] -1), в то время как я использовал только [количество данных].

Спасибо за внимание =).

...