【问题标题】:iOS NSMutableArray insertObject index out of boundiOS NSMutableArray insertObject 索引超出范围
【发布时间】:2010-12-05 13:56:33
【问题描述】:

我是 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];

对它可能有什么问题有任何想法吗?

【问题讨论】:

    标签: objective-c cocoa-touch ios nsmutablearray


    【解决方案1】:

    您在insertRowsAtIndexPaths:withRowAnimation 中拨打的电话:应介于tableView 上的beginUpdatesendUpdates 之间。

    检查TableView Programming Guide

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 谢谢,这有点帮助。但现在我得到同样的错误,但下面有 2 行。有什么想法吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-30
      相关资源
      最近更新 更多