我是新來的Objective-C編程,所以對於跛腳問題感到抱歉。iOS NSMutableArray insertObject索引超出範圍
我想寫一些簡單的應用程序,將存儲在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行。任何想法有什麼問題嗎? – IvanR 2010-12-05 14:21:42