Swift UIViewController UITableView编辑模式导致tableView部分返回nil



我有一个运行良好的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.sectionsnil:时在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可返回。当sectionsnil时,简单地返回默认值0就足够了,因为那时fetchedResultsController将有时间完成加载并用适当的数据重新加载表视图。

我以为语法是:

self.tableView.setEditing(true, animated: true)

我还没有在任何代码中对此进行建模。所以,如果没有帮助,请告诉我,我会再试一次。

最新更新