在 ios 应用程序中,我有一个 UITableView。在 cellForRowAtIndexPath
方法中,我需要使用它的 NIB 名称返回自定义单元格。为此,我使用 loadNibNamed
。 (我会在'willDisplayCellforRowAtIndexPath'中加载后填充单元格中的数据)
MyItemCell 是一个 XIB 文件 (MyItemCell.xib),包含 2 个 UIImageView 和一个 UIButton(每个项目都有一个标签)
这是我的代码:
在我的 View Controller 中
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
return [ViewHelper loadCustomCellWithNibName:@"MyItemCell" owner:self];
}
以及从NIB加载自定义单元格的方法
+ (UITableViewCell *) loadCustomCellFromNib:(NSString *)nibName owner:(id)owner
{
UITableViewCell *cell = nil;
NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:nibName owner:owner options:nil];
if([nibObjects count] > 0 )
{
cell = [nibObjects objectAtIndex:0];
}
else
{
NSLog(@"Failed to load %@ XIB file!", nibName);
}
return cell;
}
在所有测试中一切正常。但是,我收到了一些无法重现的用户崩溃。
这是崩溃:
NSInternalInconsistencyException
Could not load NIB in bundle: 'NSBundle </var/mobile/Applications/7A24cE79-131F-523F-4C00-23B523ARG123/MyApp.app> (loaded)' with name 'MyItemCell'
堆栈跟踪:
0 CoreFoundation 0x39b432a3 __exceptionPreprocess + 163 + 162
1 libobjc.A.dylib 0x33a3297f objc_exception_throw + 31 + 30
2 CoreFoundation 0x39b431c5 -[NSException initWithCoder:] + 1
3 UIKit 0x32e12491 -[UINib instantiateWithOwner:options:] + 1637 + 1636
4 UIKit 0x32e1a1d7 -[NSBundle(UINSBundleAdditions) loadNibNamed:owner:options:] + 139 + 138
5 MyApp 0x00047ded +[ViewHelper loadCustomCellFromNib:owner:] (ViewHelper.m:349)
6 MyApp 0x00034003 -[BuildViewController tableView:cellForRowAtIndexPath:] (BuildViewController.m:2432)
7 UIKit 0x32cc0545 -[UITableView(UITableViewInternal) _createPreparedCellForGlobalRow:withIndexPath:] + 413 + 412
8 UIKit 0x32ca530b -[UITableView(_UITableViewPrivate) _updateVisibleCellsNow:] + 1311 + 1310
9 UIKit 0x32cbc7c7 -[UITableView layoutSubviews] + 207 + 206
10 UIKit 0x32c78803 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 259 + 258
问题是我无法重现这次崩溃。
知道可能导致崩溃的原因吗?或避免此类错误的任何解决方案?
非常感谢您的帮助
编辑:
只是为了进一步说明,这在我正在进行的任何测试中都运行良好。此崩溃仅对 1 位用户出现 1 次,因此问题不在于代码。我只是在寻找在非常具体的情况下可能导致崩溃的原因。谢谢
最佳答案
要从 NIB 文件创建自定义单元格试试这个
- (void)viewDidLoad
{
[tableView registerNib:[UINib nibWithNibName:CellIdentifier bundle:nil] forCellReuseIdentifier:CellIdentifier];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
MyCell *cell = (MyCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
......
return cell;
}
CellIdentifier是NIB文件的名称,也用作细胞标识符。
关于ios - UITableView 从 NIB 文件加载自定义单元格抛出 NSInternalInconsistencyException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14520495/