代码适用于iPhone 5,而不适用于iPod touch 4

时间:2013-04-18 03:02:54

标签: iphone ios objective-c

我正在不同的设备上测试我的应用程序。该应用程序在我的iPhone 5上工作正常,但是,当我在我的iPod touch 4g上测试时,我得到了这个错误:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '***  [__NSArrayMinsertObject:atIndex:]: object cannot be nil'
*** First throw call stack:
(0x33f252a3 0x3bba397f 0x33e6f8d9 0x51e25 0x35e180c5 0x35e1814d 0x35e180c5 0x35e18077 0x35e18055 0x35e1790b 0x35e17e01 0x35d405f1 0x35d2d801 0x35d2d11b 0x37a1f5a3 0x37a1f1d3 0x33efa173 0x33efa117 0x33ef8f99 0x33e6bebd 0x33e6bd49 0x37a1e2eb 0x35d81301 0x4fc8d 0x3bfdab20)
libc++abi.dylib: terminate called throwing an exception

崩溃的代码就是这个:

/********/
    NSMutableArray *titulosCampoTextArray = [[NSMutableArray alloc] init];
    for (int i = 0; i < campos.count; i++) {

        SignupCell *cell = (SignupCell*)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
        [titulosCampoTextArray addObject:cell.textField.text];
    }
/********/

我在UIView内的UITableView上使用自定义原型单元格(SignupCell.h)。

无法找到错误或如何修复错误。

编辑:两台设备都在运行iOS 6.1.3,而我正在使用Xcode 4.6.1。

2 个答案:

答案 0 :(得分:5)

UITableView -cellForRowAtIndexPath:方法返回nil,如果您在调用时屏幕上看不到该单元格。

我的猜测是,在iPhone 5上,您的桌子可以同时显示所有行,而在较短的iPod touch上,最后一个或两个单元格不可见,-cellForRowAtIndexPath:因此返回nil ,这会让你的应用程序崩溃。

您不应该依赖-cellForRowAtIndexPath来请求模型数据!视图控制器负责数据,而不是表视图。

使用相同的方式访问模型数据,就像在视图控制器的-tableView:cellForRowAtIndexPath:数据源方法中设置表格视图单元格一样。

答案 1 :(得分:1)

这样做:

NSMutableArray *titulosCampoTextArray = [[NSMutableArray alloc] init];
for (int i = 0; i < campos.count; i++) {

    SignupCell *cell = (SignupCell*)[self.tableView 
        cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
    if (cell.textField.text) {
        [titulosCampoTextArray addObject:cell.textField.text];
    }
}

我不知道为什么你显然可以在iPhone 5上添加nil而不是在iPod上添加nil。可能由于某些其他原因,当您的应用在iPhone 5上运行时,您cell.textField.text永远不会有{{1}}值。