Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Objective c iOS NSMutableArray insertObject索引超出范围_Objective C_Cocoa Touch_Ios_Nsmutablearray - Fatal编程技术网

Objective c iOS NSMutableArray insertObject索引超出范围

Objective c iOS NSMutableArray insertObject索引超出范围,objective-c,cocoa-touch,ios,nsmutablearray,Objective C,Cocoa Touch,Ios,Nsmutablearray,我是Objective-C编程新手,很抱歉问了这个蹩脚的问题 我正在尝试编写一些简单的应用程序,将存储在NSMutableArray中的单个数字添加到表视图中 以下是init代码和addItem()方法的代码: 这条线 [itemArray insertObject:@"1" atIndex:0]; 产生以下错误: *** -[NSMutableArray objectAtIndex:]: index 0 beyond bounds for empty array' 为什么索引0超出空数组的

我是Objective-C编程新手,很抱歉问了这个蹩脚的问题

我正在尝试编写一些简单的应用程序,将存储在NSMutableArray中的单个数字添加到表视图中

以下是init代码和addItem()方法的代码:

这条线

[itemArray insertObject:@"1" atIndex:0];
产生以下错误:

*** -[NSMutableArray objectAtIndex:]: index 0 beyond bounds for empty array'
为什么索引0超出空数组的界限?我做错了什么

UPD

正如BP指出的,插入到数组中可能不适用于空数组,因此我添加了以下检查:

if ([itemArray count] == 0) {
    [itemArray addObject:@"1"];     
} else {
    [itemArray insertObject:@"1" atIndex:0];
}
所以现在我得到了同样的错误信息,但在第行

[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

有什么问题吗?

initWithCapacity方法只为对象留出内存,实际上并没有创建数组中指定的对象数


我不确定是否可以插入到一个尚未包含任何对象的数组中,因此如果数组计数为0,则可能需要尝试使用addObject方法,而insertObject方法则不然。

InsertRowsAndExpaths:withRowAnimation
:中进行的调用应介于
开始更新
结束更新
调用
表视图
之间


检查一下。

谢谢,这有点帮助。但现在我得到了同样的错误,但下面有两行。你知道有什么问题吗?
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];