2014-10-03 101 views
0

我有一个UITableView工作得很好。当启用使用viewDidLoad中的内部下面的代码编辑模式()方法:Swift UIViewController UITableView编辑模式导致tableView部分返回无

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不是零,但部分是。

如果编辑模式被禁用,情况并非如此。

可能是什么原因?

回答

1

要停止此特定错误,你可以简单地返回numberOfSectionsInTableView默认值时fetchedResultsController.sectionsnil

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

func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
    return fetchedResultsController.sections?.count ?? 0 // 0 is the default 
} 

那并不能解释为什么当您的tableView处于editing模式时,您的fetchedResultsController正在返回nilsections阵列。

我怀疑sections可能是nil,因为您在viewDidLoad中设置editing并且这触发了表视图重新加载。此时,fetchedResultsController可能没有足够的时间获取任何结果,因此它没有任何sections返回。当sectionsnil时,仅仅返回0的默认值就足够了,因为那时fetchedResultsController将有时间完成其加载并用正确的数据重新加载表视图。

+0

太棒了,现在解决了我的问题。你对你的假设可能是正确的。我现在将其标记为正确。 – Sev 2014-10-04 01:33:03

0

我认为语法是:

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

我没有任何代码建模这一点。所以如果它没有帮助,让我知道,我会再试一次。

相关问题