获取“索引 0 超出空数组范围”非空数组错误
我有这段代码可以在应用程序的根视图控制器中的表视图中添加一行:
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
NSArray *myArray = [NSArray arrayWithObject:indexPath];
NSLog(@"count:%d", [myArray count]);
[self.tableView insertRowsAtIndexPaths:myArray withRowAnimation:UITableViewRowAnimationFade];
[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
当它与模拟器一起运行时,我得到以下输出:
数量:1
* 由于未捕获的异常“NSRangeException”而终止应用程序,原因:“* -[NSMutableArray objectAtIndex:]:索引 0 超出空数组的范围”
这发生在 [self.tableView insertRowsAtIndexPaths :myArray withRowAnimation:UITableViewRowAnimationFade];
行,但 NSLog
语句显示名为 myArray
的 NSArray
不为空。我错过了什么吗?以前有人遇到过这种情况吗?
I have this code to add a row to a table view in the root view controller of my application:
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
NSArray *myArray = [NSArray arrayWithObject:indexPath];
NSLog(@"count:%d", [myArray count]);
[self.tableView insertRowsAtIndexPaths:myArray withRowAnimation:UITableViewRowAnimationFade];
[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
When it is run with the simulator I get this output:
count:1
* Terminating app due to uncaught exception 'NSRangeException', reason: '* -[NSMutableArray objectAtIndex:]: index 0 beyond bounds for empty array'
This is occurring at the [self.tableView insertRowsAtIndexPaths:myArray withRowAnimation:UITableViewRowAnimationFade];
line, but the NSLog
statement shows that the NSArray
called myArray
is not empty. Am I missing something? Has anyone ever encountered this before?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在日志语句之前的行中,您将创建一个仅在此方法的范围内有效的新数组。用于表视图数据源方法的数组是不同的数组,因此该数组中的对象数量根本不重要,即使它具有(正如我怀疑的)相同的名称。
In the line before the log statement, you're creating a new array that's only valid in the scope of this method. The array you're using for the table view's data source methods is a different one, so the number of objects in this array doesn't matter at all, even if it has (as I suspect) the same name.
调用 insertRowsAtIndexPaths 会触发调用 UITableViewController 委托/数据源方法。这样 UITableView 就可以获取新行的数据。您需要将数据插入到数据模型中,并确保 numberOfRowsInSection 返回新增加的值。
NSRangeException 错误指的是您用来存储表行数据的任何 NSMutableArray,而不是索引路径数组。
Calling insertRowsAtIndexPaths triggers your UITableViewController delegate/datasource methods to be called. This is so that the UITableView can obtain the data for the new row. You need to insert data into your data model and make sure numberOfRowsInSection is returning the new increased value.
The NSRangeException error is referring to whatever NSMutableArray you are using to store your data for table rows rather than the array of index paths.