2010-12-05 90 views
0

我是新來的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

您在insertRowsAtIndexPaths:withRowAnimation中撥打的電話應在beginUpdatesendUpdates之間撥打電話tableView

檢查TableView Programming Guide

0

initWithCapacity方法只爲對象留出內存,它實際上並不創建數組中指定的對象數。

我不知道你是否可以插入一個沒有對象的數組中,所以你可能想嘗試在數組數爲0的情況下使用addObject方法,否則使用insertObject方法。

+0

謝謝,有點幫助。但現在我得到相同的錯誤,但下面2行。任何想法有什麼問題嗎? – IvanR 2010-12-05 14:21:42