iOS开发求助:Xcode运行报错Terminating with uncaught exception of type NSException
解决UITableView无法复用PlayerCell的崩溃问题
首先帮你理清问题:那个libMobileGestalt MobileGestalt.c:890: MGIsDeviceOneOfType is not supported on this platform只是系统级警告,完全不会导致App崩溃,可以直接忽略。真正让程序崩溃的是下面这个核心错误:
unable to dequeue a cell with identifier PlayerCell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard
这个错误的意思是:你的UITableView尝试取出标识符为PlayerCell的复用Cell,但系统找不到该Cell的注册信息——要么你没在Storyboard里配置原型Cell,要么没在代码里注册对应的Cell类/XIB文件。
具体解决步骤分两种情况:
情况1:使用Storyboard中的原型Cell
- 打开项目Storyboard,找到对应的UITableView
- 选中里面的原型Cell(如果没有,先拖一个UITableViewCell到TableView中)
- 在右侧Attributes Inspector(属性检查器)里,把
Identifier字段设置为PlayerCell(注意大小写要和代码里完全一致,Swift区分大小写) - 如果你的Cell是自定义类,还要在Identity Inspector(身份检查器)里把Class设置为你的
PlayerCell类 - 最后确认ViewController已正确关联到Storyboard中的TableView,并且TableView的
dataSource和delegate已设置(可以通过Storyboard拖线,或者在viewDidLoad里添加tableView.dataSource = self、tableView.delegate = self)
情况2:使用XIB文件或纯代码创建Cell
如果Cell是用XIB文件设计的,在ViewController的viewDidLoad方法里添加注册代码:
override func viewDidLoad() { super.viewDidLoad() // 注册XIB文件 tableView.register(UINib(nibName: "PlayerCell", bundle: nil), forCellReuseIdentifier: "PlayerCell") }
如果是纯代码编写的自定义Cell类,注册方式改为:
override func viewDidLoad() { super.viewDidLoad() // 注册Cell类 tableView.register(PlayerCell.self, forCellReuseIdentifier: "PlayerCell") }
关于版本差异的问题
你使用的Xcode 10.1/iOS 12和教程的Xcode 9/iOS 11在UITableView的Cell复用机制上没有本质区别,所以版本差异不是导致崩溃的原因,问题出在Cell的配置/注册环节。
最后再检查一下你cellForRowAt方法里的代码,确保取出Cell的标识符是正确的PlayerCell,比如:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "PlayerCell", for: indexPath) as! PlayerCell // 这里配置Cell内容 return cell }
内容的提问来源于stack exchange,提问作者Saiful
相关产品推荐
相关产品推荐

