将NSNumber对象添加到NSMutableArray

时间:2013-02-06 07:51:50

标签: objective-c xcode cocoa-touch

这段代码会导致错误,但它应该是正确的。

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

genreArrayNSMutableArray

但是在接触到一个单元格时我会收到此错误

*** 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

有谁知道为什么这不起作用?

1 个答案:

答案 0 :(得分:3)

因为你的数组是不可变的...... 检查实例化genreArray的代码:两种类型声明,AND实例化必须使用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];