我有一个运行良好的UITableView。当我在viewDidLoad()方法中使用以下代码启用编辑模式时:
self.tableView.editing = true
我得到以下错误:
fatal error: unexpectedly found nil while unwrapping an Optional value
在这条线上:
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return fetchedResultsController.sections!.count // error here
}
我检查并获取了ResultsController不是零,但sections是.
如果禁用编辑模式,则情况并非如此。
原因可能是什么?
要停止此特定错误,只需在fetchedResultsController.sections
为nil
:时在numberOfSectionsInTableView
中返回默认值
注意使用sections?
而不是sections!
,以及零凝聚算子??
:
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return fetchedResultsController.sections?.count ?? 0 // 0 is the default
}
这并不能解释为什么当tableView
处于editing
模式时,fetchedResultsController
返回nil
sections
数组。
我怀疑sections
可能是nil
,因为您在viewDidLoad
中设置了editing
,这会触发表视图重载。此时,fetchedResultsController
可能根本没有足够的时间获取任何结果,因此它没有任何sections
可返回。当sections
为nil
时,简单地返回默认值0
就足够了,因为那时fetchedResultsController
将有时间完成加载并用适当的数据重新加载表视图。
我以为语法是:
self.tableView.setEditing(true, animated: true)
我还没有在任何代码中对此进行建模。所以,如果没有帮助,请告诉我,我会再试一次。