2016-03-18 5 views
1

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

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

for (int i=0; i<rows; i++) 
       { 
        NSIndexPath *tmpIndexPath = [NSIndexPath indexPathForRow:i 
                    inSection:section]; 
        [tmpArray addObject:tmpIndexPath]; 
       } 

но работать нормально, если цикл, как в Tableview: (UITableView *) Tableview didSelectRowAtIndexPath: (NSIndexPath *) indexPath

for (int i=1; i<rows; i++) 
       { 
        NSIndexPath *tmpIndexPath = [NSIndexPath indexPathForRow:i 
                    inSection:section]; 
        [tmpArray addObject:tmpIndexPath]; 
       } 

Нагрузочного приложение из-за неперехваченное исключение 'NSInternalInconsistencyException', почему-то : «Неверное обновление: недопустимое количество строк в разделе 0. Количество строк, содержащихся в существующем разделе после обновления (6), должно быть равно количеству строк, содержащихся в этом разделе, перед обновлением (1), плюс или минус количество вставленных или удаленных строк из в разделе (6 вставлено, 0 удалено) и плюс или минус количество строк, перемещенных в или из этого раздела (0 перемещено в, 0 выведено). '

*** First throw call stack: 
(
    0 CoreFoundation      0x02d9c5e4 __exceptionPreprocess + 180 
    1 libobjc.A.dylib      0x02b1f8b6 objc_exception_throw + 44 
    2 CoreFoundation      0x02d9c448 +[NSException raise:format:arguments:] + 136 
    3 Foundation       0x0270023e -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 116 
    4 UIKit        0x0196320d -[UITableView _endCellAnimationsWithContext:] + 13402 
    5 UIKit        0x01972c60 -[UITableView _updateRowsAtIndexPaths:updateAction:withRowAnimation:] + 337 
    6 UIKit        0x01972c9f -[UITableView insertRowsAtIndexPaths:withRowAnimation:] + 55 
    7 UIKit        0x0dceada5 -[UITableViewAccessibility(Accessibility) insertRowsAtIndexPaths:withRowAnimation:] + 65 
    8 BPSSalesDocs      0x00222d10 -[MiddlePageViewController_iPhone tableView:didSelectRowAtIndexPath:] + 1152 
    9 UIKit        0x01973ec1 -[UITableView _selectRowAtIndexPath:animated:scrollPosition:notifyDelegate:] + 1513 
    10 UIKit        0x01974034 -[UITableView _userSelectRowAtPendingSelectionIndexPath:] + 279 
    11 UIKit        0x01978018 __38-[UITableView touchesEnded:withEvent:]_block_invoke + 43 
    12 UIKit        0x018aed33 ___afterCACommitHandler_block_invoke + 15 
    13 UIKit        0x018aecde _applyBlockToCFArrayCopiedToStack + 403 
    14 UIKit        0x018aeb0a _afterCACommitHandler + 532 
    15 CoreFoundation      0x02d6453e __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 30 
    16 CoreFoundation      0x02d6448f __CFRunLoopDoObservers + 399 
    17 CoreFoundation      0x02d423b4 __CFRunLoopRun + 1076 
    18 CoreFoundation      0x02d41b33 CFRunLoopRunSpecific + 467 
    19 CoreFoundation      0x02d4194b CFRunLoopRunInMode + 123 
    20 GraphicsServices     0x04b449d7 GSEventRunModal + 192 
    21 GraphicsServices     0x04b447fe GSEventRun + 104 
    22 UIKit        0x0189294b UIApplicationMain + 1225 
    23 BPSSalesDocs      0x001c8a3d main + 141 
    24 libdyld.dylib      0x03822725 start + 0 
) 
libc++abi.dylib: terminating with uncaught exception of type NSException 

Ниже приведен код для UITable View didSelectRowAtIndexPath

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
    _ParentCollection = [[Content alloc] initWithDictionary:[_collections objectAtIndex:indexPath.section]]; 
    [self performSelectorOnMainThread:@selector(loadChildCollection:) withObject:[_ParentCollection collectionId] waitUntilDone:YES]; 
    if ([_childCollections count] > 0) { 
     if ([self tableView:tableView canCollapseSection:indexPath.section]) { 
      if (!indexPath.row) { 
       [tableView deselectRowAtIndexPath:indexPath animated:YES]; 

       NSInteger section = indexPath.section; 
       BOOL currentlyExpanded = [_expandedSections containsIndex:section]; 
       NSInteger rows; 

       NSMutableArray *tmpArray = [NSMutableArray array]; 

       if (currentlyExpanded) 
       { 
        rows = [self tableView:tableView numberOfRowsInSection:section]; 
        [_expandedSections removeIndex:section]; 
       } 
       else 
       { 
        [_expandedSections addIndex:section]; 
        rows = [self tableView:tableView numberOfRowsInSection:section]; 
       } 

       for (int i=0; i<rows; i++) 
       { 
        NSIndexPath *tmpIndexPath = [NSIndexPath indexPathForRow:i 
                    inSection:section]; 
        [tmpArray addObject:tmpIndexPath]; 
       } 

       if (currentlyExpanded) 
       { 
        [tableView deleteRowsAtIndexPaths:tmpArray 
            withRowAnimation:UITableViewRowAnimationTop]; 
       } 
       else 
       { 
        [tableView insertRowsAtIndexPaths:tmpArray 
            withRowAnimation:UITableViewRowAnimationTop]; 
       } 
      } 
      else { 
       self.childCollectionContent = [[Content alloc] initWithDictionary:[self.childCollections objectAtIndex:indexPath.row]]; 

       UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:[DeviceHelper getStoryboardName] bundle:nil]; 

       ContentViewController *contentViewController = (ContentViewController*)[mainStoryboard instantiateViewControllerWithIdentifier: @"ContentViewController"]; 
       [contentViewController setNavigationalContents:_childCollections]; 
       [contentViewController setCollectionId:[NSString stringWithFormat:@"%@", [self.childCollectionContent collectionId]]]; 
       [contentViewController setContentId:[self.childCollectionContent contentId]]; 
       [contentViewController setTitle:[self.childCollectionContent title]]; 
       [contentViewController setContentType:[self.childCollectionContent type]]; 


       //  [contentViewController setContentUpdateDelegate:_contentUpdateDelegate]; 
       //  [contentViewController setContentNavigationDelegate:_contentNavigationDelegate]; 

       if ([[[AppService sharedService] mainViewController] isKindOfClass:[UINavigationController class]]) { 
        UINavigationController* navigationController = (UINavigationController*)[[AppService sharedService] mainViewController]; 
        navigationController.navigationBarHidden = NO; 
        [navigationController pushViewController:contentViewController animated:YES]; 
        NSDictionary *attributes = @{NSForegroundColorAttributeName: [UIColor whiteColor]}; 
        [[navigationController navigationBar] setTitleTextAttributes:attributes]; 

       } else { 
        [[[AppService sharedService] mainViewController] presentViewController:contentViewController animated:YES completion:nil]; 
       } 

       AnalyticsClicked* analyticsClicked = [[AnalyticsClicked alloc] init]; 
       analyticsClicked.collectionId = [self.childCollectionContent collectionId]; 
       analyticsClicked.contentId = [self.childCollectionContent contentId]; 
       analyticsClicked.contentNumber = [self.childCollectionContent contentNumber]; 

       [[[AppService sharedService] analytics] platformAnalyticsContentClickPush:analyticsClicked]; 
      } 
     } 
    } 
} 

и numberOfRowsInSections код

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
// return [_collections count]; 
    if ([self tableView:tableView canCollapseSection:section]) { 
     if ([_expandedSections containsIndex:section]) { 
      return [_childCollections count]; 
     } 
    } 
    return 1; 
} 
+0

Вы не должны сами ссылаться на методы источника данных или делегата. Вы мутируете массив и снова вызываете методы. Используйте свой собственный счет массива вместо вызова 'self tableView: tableView numberOfRowsInSection: section]' – erenkabakci

+0

Я пробовал то, что вы предлагаете, но все равно получая такую ​​же ошибку. Я думаю, что ошибка находится в [tableView insertRowsAtIndexPaths: tmpArray withRowAnimation: UITableViewRowAnimationTop]; Я не могу это идентифицировать. – ranjeet

ответ

1

я наконец-то смог преодолевающим эту ошибку. В моем didSelectRowAtIndexPath я изменил ниже кода

if (currentlyExpanded) 
       { 
        [tableView deleteRowsAtIndexPaths:tmpArray 
            withRowAnimation:UITableViewRowAnimationTop]; 
       } 
       else 
       { 
        [tableView insertRowsAtIndexPaths:tmpArray 
            withRowAnimation:UITableViewRowAnimationTop]; 
       } 

с

if (currentlyExpanded) 
       { 
        [tableView beginUpdates]; 
        [tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationTop]; 
        [tableView deleteRowsAtIndexPaths:tmpArray 
            withRowAnimation:UITableViewRowAnimationTop]; 
        [tableView endUpdates]; 
       } 
       else 
       { 
        [tableView beginUpdates]; 
        [tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationTop]; 
        [tableView insertRowsAtIndexPaths:tmpArray 
            withRowAnimation:UITableViewRowAnimationTop]; 
        [tableView endUpdates]; 
       } 

Я думаю, что проблема была из-за несоответствие количества строк перед обновлением и после обновления, которые разрешаются только по телефону

[tableView reloadSections: [NSIndexSet indexSetWithIndex: indexPath.section]

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

Смежные вопросы

 Смежные вопросы