iOS 8 & Xcode 6:UINib加载xib文件问题

使用UINib类静态方法nibWithNibName:bundle:加载xib(nib)文件,第一个参数无须加文件后缀。若加后缀,则程序报错;第二个参数为空时,程序从mainBundle指向的路径中搜索文件。

正确的写法:

UINib *storyCellNib = [UINib nibWithNibName:@"StoryCell" bundle:nil];

[self.tableView registerNib:storyCellNib forCellReuseIdentifier:STORY_CELL];

错误的写法:

UINib *storyCellNib = [UINib nibWithNibName:@"StoryCell.xib" bundle:nil]; // 改成StoryCell.nib报相同的错误
[self.tableView registerNib:storyCellNib forCellReuseIdentifier:STORY_CELL];

报错信息:

*** Terminating app due to uncaught exception ‘NSInternalInconsistencyException‘, reason: ‘Could not load NIB in bundle: ‘NSBundle </Users/michael/Library/Developer/CoreSimulator/Devices/7400CB88-E5F3-4FB5-8A84-FBF2B7AC3134/data/Containers/Bundle/Application/2193EB85-C6B4-4A12-8753-02AEC798B15F/zhihudaily.app> (loaded)‘ with name ‘StoryCell.nib‘‘

在Xcode 6中,如果xib文件只定义了一个视图,则不指定File‘s Owner,也指定Custom Class的Class,只指定了Indentifer,使用上面的加载方式也可正常工作。不过,此视图无法添加新的输出接口(IBOutlet)和动作响应(IBAction)。而且,当xib文件中存在多个不同视图时,上述加载方式将报如下错误:

*** Assertion failure in -[UITableView _dequeueReusableViewOfType:withIdentifier:], /SourceCache/UIKit_Sim/UIKit-3318.16.14/UITableView.m:6090
2014-11-24 23:21:18.322 zhihudaily[13323:1498086] *** Terminating app due to uncaught exception ‘NSInternalInconsistencyException‘, reason: ‘invalid nib registered for identifier (StoryCell) - nib must contain exactly one top level object which must be a UITableViewCell instance‘

  

所以,最好为自定义视图指定Custom Class或File‘w Owner。

结论:当使用nibWithNibName:bundle:方法加载xib文件时,此文件只允许定义一个顶级的视图,若定义多个顶级视图,则产生异常。

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。