2014-10-03 32 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) 

我沒有任何代碼建模這一點。所以如果它沒有幫助,讓我知道,我會再試一次。