2013-02-06 151 views
2

這段代碼會導致錯誤,但它應該是正確的。將NSNumber對象添加到NSMutableArray

(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    NSNumber *rowNumber = [[NSNumber alloc] initWithInt:indexPath.row]; 
    [genreArray addObject:rowNumber]; 
    [self.tableView reloadData]; 
} 

genreArrayNSMutableArray

但對一個cell觸摸我得到這個錯誤

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFArray insertObject:atIndex:]: mutating method sent to immutable object' 
*** First throw call stack: 
(0x1c9c012 0x10d9e7e 0x1c9bdeb 0x1d1c9a5 0x1d1c8b0 0x7b4c 0xcd285 0xcd4ed 0xad75b3 0x1c5b376 0x1c5ae06 0x1c42a82 0x1c41f44 0x1c41e1b 0x1bf67e3 0x1bf6668 0x1dffc 0x271d 0x2645) 
libc++abi.dylib: terminate called throwing an exception 

有沒有人有一個想法,爲什麼這是不工作?

+0

做除了答案簡單,你可以改變' NSNumber * rowNumber = [[NSNumber alloc] initWithInt:indexPath.row];'帶'NSNumber * rowNumber = @(indexPath.row);' – graver

+1

你分配了genreArray = [[NSMutableArray alloc] init];' – laxonline

+0

問題是我把它分配爲NSMutableArray,但後來我寫道:genreArray = someOtherArray; someOtherArray是一個數組,而不是一個可變數組。現在我分配它[NSMutableArray arrayWithArray:someOtherArray];這樣可行! – Wed

回答

3

因爲你的陣列是不可變的... 檢查要實例化genreArray代碼:既有類型聲明,和實例化必須以NSMutableArray

//valid declaration + instantiation 
NSMutableArray *genreArray = [NSArray array]; 

//valid at compile-time : genreArray is supposed to be mutable 
//however will result in runtime error : genreArray is actually immutable 
[genreArray addObject:anObject]; 
+0

我發現了這個問題。有一個worng初始化,謝謝=) – Wed