【问题标题】:Why endUpdates crashes on array out of bounds when I don't have any array?当我没有任何数组时,为什么 endUpdates 在数组越界时崩溃?
【发布时间】:2012-04-07 11:41:22
【问题描述】:

我有一个以 C++ 对象为数据源的 UITableView,因此没有任何类型的 NSArray。每当我想在现有列表的末尾插入一行时,我就会崩溃

Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 5 beyond bounds [0 .. 4]

它在 [tableView endUpdates] 上崩溃。但是,我的实现中没有任何 NSArray 或任何调用 objectAtIndex 的代码。我不知道我为什么会崩溃。

我只有一个部分,并且总是将新行添加到第 0 部分的末尾。返回的行数是正确的,因此完全同步。

在我看到的日志中,[tableView endUpdates] 调用 numberOfRowsInSection 正确返回了前一个计数加一的计数。但是,它再也不会调用 cellForRowAtIndexPath 并且无法通过 [tableView endUpdates];

-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"...");

    ........


    NSArray *insertIndexPaths = [NSArray arrayWithObjects:[NSIndexPath indexPathForRow:oldCount + i inSection:[indexPath section]], nil];

    NSLog(@"Insert: %d %d %d", i, (int) oldCount, (int) newCount);

    [tableView beginUpdates];        
    [tableView insertRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationNone];                
    [tableView endUpdates];

}

-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    int i = _reader->allRead() ? _reader->getWindowCount() : _reader->getWindowCount() + 30;    
    return i;
}

-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{   
    return 1;
//    return __results__ ? 1 : 0;
}

【问题讨论】:

  • 只有这一行的问题 NSArray *insertIndexPaths = [NSArray arrayWithObjects:[NSIndexPath indexPathForRow:oldCount + i inSection:[indexPath section]], nil];
  • 我正在添加到最后一个元素并在同一部分 (0) 中。即使我将 oldCount + i 更改为 1 或 2,我也得到了相同的结果。
  • 我在 NSIndexPath *indexpath_delete = [NSIndexPath indexPathForRow:oldCount + i inSection:[indexPath section]] 之前遇到过这个问题;
  • [tableView beginUpdates]; [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexpath_delete] withRowAnimation:UITableViewRowAnimationNone]; [tableView endUpdates];
  • 像上面那样尝试可能对你有帮助..

标签: iphone objective-c


【解决方案1】:

当您更新 tableview 时,您也必须更新数据源。 在您的代码中没有显示数据源更新方法,所以我认为应该考虑到这一点。

【讨论】:

  • 数据源已经更新......这就是为什么数据源返回正确的计数(以前的计数 + 1)。这是正确的。我只是好奇数组崩溃是从哪里来的。
  • 构建一个调试配置,告诉 Xcode 中断异常,并让 Xcode 显示崩溃的来源。
  • @KenThomases Xcode 调试很糟糕。 10% 的时间它可能会显示它崩溃的线路。
【解决方案2】:

尝试[[self tableView] reloadData] 而不是[[self tableView] endUpdates]

【讨论】:

    猜你喜欢
    • 2015-12-07
    • 1970-01-01
    • 2022-11-21
    • 1970-01-01
    • 2014-11-17
    • 1970-01-01
    • 1970-01-01
    • 2013-01-16
    • 2016-04-26
    相关资源
    最近更新 更多