我有一个工作正常的 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
}
我检查了一下,fetchedResultsController 不是 nil,但是sections 是。
如果禁用编辑模式,则不会出现这种情况。
可能是什么原因?
最佳答案
要停止此特定错误,您只需在 fetchedResultsController.sections
为 nil
时在 numberOfSectionsInTableView
中返回默认值即可:
请注意使用 sections?
而不是 sections!
,以及 Nil Coalescing Operator ??
:
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return fetchedResultsController.sections?.count ?? 0 // 0 is the default
}
这并不能解释为什么当您的 tableView
位于时,您的 fetchedResultsController
返回 nil
sections
数组编辑
模式。
我怀疑 sections
可能是 nil
因为您在 viewDidLoad
中设置 editing
并且这会触发 TableView 重新加载。此时,fetchedResultsController
可能根本没有足够的时间来获取任何结果,因此它没有任何部分
可返回。当 sections
为 nil
时,简单地返回默认值 0
可能就足够了,因为那时 fetchedResultsController
将有时间完成加载并使用正确的数据重新加载表格 View 。
关于objective-c - Swift UIViewController UITableView编辑模式导致tableView部分返回nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26187882/