iOS NSMutableArray insertObject索引超出范围

时间:2010-12-05 13:56:33

标签: objective-c cocoa-touch ios nsmutablearray

我是Objective-C编程的新手,对于这个蹩脚的问题感到抱歉。

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

这是addItem()方法的初始化代码和代码:

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"Test App";
    self.navigationItem.leftBarButtonItem = self.editButtonItem;

    addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd   target:self action:@selector(addItem)];
    self.navigationItem.rightBarButtonItem = addButton;

    self.itemArray = [[NSMutableArray alloc] initWithCapacity:100];
}

- (void)addItem {
    [itemArray insertObject:@"1" atIndex:0];

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}

这一行

[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];

关于它可能出现什么问题的任何想法?

2 个答案:

答案 0 :(得分:2)

您在insertRowsAtIndexPaths:withRowAnimation中拨打的电话应该在beginUpdates的{​​{1}}和endUpdates来电之间。

检查TableView Programming Guide

答案 1 :(得分:0)

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

我不确定你是否可以插入到一个没有对象的数组中,所以你可能想要在数组计数为0时尝试使用addObject方法,否则尝试使用insertObject方法。