【问题标题】:Swift UIViewController UITableView editing mode causes tableView sections to return nilSwift UIViewController UITableView 编辑模式导致 tableView 部分返回 nil
【发布时间】:2014-10-03 22:59:28
【问题描述】:

我有一个运行良好的 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,但 section 是。

如果编辑模式被禁用,则不是这种情况。

可能是什么原因?

【问题讨论】:

    标签: objective-c uitableview swift ios8


    【解决方案1】:

    要停止此特定错误,您只需在 fetchedResultsController.sectionsnil 时在 numberOfSectionsInTableView 中返回默认值即可:

    注意使用sections? 代替sections!,以及Nil Coalescing Operator ??

    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 将有时间完成其加载并使用适当的数据重新加载表格视图。

    【讨论】:

    • 太棒了,现在解决了我的问题。您的假设可能是正确的。我暂时将其标记为正确。
    【解决方案2】:

    我认为语法是:

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

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

    【讨论】:

      猜你喜欢
      • 2018-02-03
      • 2016-06-06
      • 1970-01-01
      • 1970-01-01
      • 2017-07-03
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多