如果初始表为空,则将行添加到UITableView崩溃

如果初始表为空,则将行添加到UITableView崩溃,uitableview,row,add,Uitableview,Row,Add,我正在使用下面的代码刷新我刚刚添加了一行的tableview。如果表中至少已有一行,则该代码用于向表中添加一行。但是,如果它最初是一个空表,它就会崩溃 NSArray *indexPaths = [NSArray arrayWithObjects: [NSIndexPath indexPathForRow:[commentsArray count] inSection:0], nil]; [commentsTableView beginUpdates]; [commentsArray add

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

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).'

有人能帮我吗?

只要确保更新时使用的数组与重新加载表时使用的数组相同即可

//自定义表视图中的行数

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

    return [commentsArray count];
}

如果这无法解决您的问题,请在此处添加一些代码。

只需确保用于更新的数组与重新加载表时使用的数组相同即可

//自定义表视图中的行数

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

    return [commentsArray count];
}

如果这不能解决您的问题,请在此处放置一些代码。

好吧,错误是告诉您UIKit调用
表视图时:numberOfRowsInSection
在更新前后都返回
0
。所以,要么你的方法有错误,要么你的更新有错误。您在对上一个答案的评论中说,您的
表视图:numberofrowsinssection
是正确的,那么它必须是更新。如果
commentsArray
在第一次更新中为nil,可能是因为某种原因。或许可以尝试以下方法:

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

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

好的,错误告诉您UIKit调用
tableView:numberOfRowsInSection
在更新之前和之后返回
0
。所以,要么你的方法有错误,要么你的更新有错误。您在对上一个答案的评论中说,您的
表视图:numberofrowsinssection
是正确的,那么它必须是更新。如果
commentsArray
在第一次更新中为nil,可能是因为某种原因。或许可以尝试以下方法:

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

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

感谢您的回复。我不确定我应该发布什么其他代码来澄清这一点。。我的
行数部分
是正确的。实际上,我正在使用
ASIHTTPRequest
发出POST请求,上面的代码块在成功响应委托方法中被调用。流程是我使用post发布评论,然后当它返回成功时,我重新分析提要,将新评论
newestEntry
添加到
commentsArray
,然后更新
commentsTableView
。感谢您的回复。我不确定我应该发布什么其他代码来澄清这一点。。我的
行数部分
是正确的。实际上,我正在使用
ASIHTTPRequest
发出POST请求,上面的代码块在成功响应委托方法中被调用。流程是我使用post发布评论,然后当它返回成功时,我重新分析提要,将新评论
newestEntry
添加到
commentsArray
,然后更新
commentsTableView
。谢谢。事实证明,当HTTP请求以空字符串响应时,甚至没有分配我的数组!非常感谢。不客气!我不喜欢Objective-C允许你毫无怨言地使用nil做事情,所以在被咬了几次之后,我养成了在任何地方使用NSAssert的习惯,一个nil对象都会咬我。最近我被咬的次数少多了;-)谢谢,谢谢。事实证明,当HTTP请求以空字符串响应时,甚至没有分配我的数组!非常感谢。不客气!我不喜欢Objective-C允许你毫无怨言地使用nil做事情,所以在被咬了几次之后,我养成了在任何地方使用NSAssert的习惯,一个nil对象都会咬我。最近我被咬的次数少多了;-)