【问题标题】:Add row to UITableView crash if initially empty table如果最初为空表,则将行添加到 UITableView 崩溃
【发布时间】:2011-05-11 10:44:28
【问题描述】:

我正在使用下面的代码来刷新我刚刚添加了一行的表格视图。如果表中已经至少有 1 行,则该代码适用于向表中添加一行。但是,如果它最初是一个空表,它会崩溃。

NSArray *indexPaths = [NSArray arrayWithObjects: [NSIndexPath indexPathForRow:[commentsArray count] inSection:0], nil];

[commentsTableView beginUpdates];

[commentsArray addObject:newestEntry];
[commentsTableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationBottom];

[commentsTableView endUpdates];

[commentsTableView scrollToBottom:YES];

我得到的崩溃响应是:

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

有人可以帮我吗?

【问题讨论】:

    标签: uitableview row add


    【解决方案1】:

    嗯,错误是告诉你 UIKit 调用 tableView:numberOfRowsInSection 在更新前后都返回 0 的时间。因此,要么您在该方法或更新中出错。您在对先前答案的评论中说您的tableView:numberOfRowsInSection 是正确的,那么它一定是更新。如果 commentsArray 在第一次更新中由于某种可能解释的原因为零。不妨试试以下方法:

    NSAssert(commentsArray, @"commentsArray is nil");
    [commentsArray addObject:newestEntry];
    

    断言将在发布版本中被忽略,因此请使用调试版本。

    【讨论】:

    • 谢谢谢谢。事实证明,当 HTTP 请求以空字符串响应时,我的数组甚至没有被分配!谢谢!
    • 不客气!我不喜欢 Objective-C 允许你用 nil 做事而不会抱怨,所以在被咬了几次之后,我养成了在 nil 对象会咬我的任何地方使用 NSAssert 的习惯。我最近被咬的少了很多;-)
    【解决方案2】:

    只需确保您用于更新的数组与您在重新加载表格时使用的数组相同。

    // 自定义表格视图的行数。

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
        return [commentsArray count];
    }
    

    如果这不能解决你的问题,请在这里放一些代码。

    【讨论】:

    • 感谢您的回复。我不确定我应该发布什么其他代码来澄清这一点。我的numberOfRowsInSection 是正确的。我实际上是使用ASIHTTPRequest 发出POST 请求,并且在成功响应委托方法中调用了上述代码块。流程是我使用 POST 发表评论,然后当它返回成功时,我重新解析提要,将新评论 newestEntry 添加到 commentsArray,然后更新 commentsTableView。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-22
    • 1970-01-01
    相关资源
    最近更新 更多