【发布时间】: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