在 iPhone 5 上可运行的代码,在 iPod touch 4 上无法运行。

4

我正在不同设备上测试我的应用程序。这个应用在我的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];
    }
/********/

我正在使用自定义原型单元格(SignupCell.h),在一个UIView内的UITableView中。
找不到错误,也不知道如何修复它。
编辑:两台设备都运行着iOS 6.1.3,并且我正在使用Xcode 4.6.1。

2个设备的iOS版本是什么? - Raptor
@ShivanRaptor 两个设备都是iOS 6.1.3。 - Oscar Swanros
2个回答

5

UITableView-cellForRowAtIndexPath:方法在调用时,如果单元格不可见,则返回nil

我猜测,在iPhone 5上,您的表格可以一次显示所有行,而在较短的iPod Touch上,最后一两个单元格不可见,因此-cellForRowAtIndexPath:返回nil,导致应用程序崩溃。

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

使用与您在视图控制器的-tableView:cellForRowAtIndexPath:数据源方法中设置表视图单元格文本相同的方式访问模型数据。


同意@MusiGenesis的观点。事实上就是这样发生的。非常感谢。 - Oscar Swanros

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 上却不能。可能是因为在 iPhone 5 上运行应用程序时,cell.textField.text 没有出现 nil 值,而在 iPod 上出现了其他原因。


实际上,在测试时,我在两个设备上按照相同的顺序填写了表格,但仍然出现了这个错误。 - Oscar Swanros
2
查看我的答案,了解为什么-cellForRowAtIndexPath:可能会返回nil。 - Fabian Kreiser

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接