2017-03-31 63 views
0

我仍然獲得在的tableView的錯誤,我想不通爲什麼:仍然得到錯誤空數組

@objc class MyViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { 

var productsToDisplay: [SKProduct]! 

override func viewWillAppear(_ animated: Bool) { 
    // an assync call to load products to the productsToDisplay 
} 


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "PurchaseItemTableViewCell", for: indexPath) as? PurchaseItemTableViewCell else { 
     fatalError("Coulnd't parse table cell!") 
    } 

    // here the app always show an error without any specification 
    if(!(self.productsToDisplay != nil && self.productsToDisplay!.count > 0))  { 
     return cell 
    } 

    cell.nameLabel.text = "my text" 

    return cell 

} 

} 

我做錯了嗎?或者在數據加載之前如何解決表的錯誤/未加載內容?

非常感謝您

+0

如果它是零,你不會返回任何東西。在tableview委託方法部分使用numberOfRows並返回productsToDisplay.count。 – rMickeyD

+0

抱歉,它在那裏,我只是沒有複製它 – David

+0

@大衛爲了安全起見,您應該返回'productsToDisplay?.count ?? 0'。 –

回答

0

基本上永遠永遠永遠聲明一個數據源數組(隱含展開)可選。聲明它爲非可選空列:

var productsToDisplay = [SKProduct]() 

好處是非可選類型不能崩潰。


numbersOfRows回報的項目數:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return productsToDisplay.count 
    } 

如果數組是空的cellForRow永遠不會被調用。


cellForRow第一套標籤然後返回電池並檢查0和nil不需要:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "PurchaseItemTableViewCell", for: indexPath) as! PurchaseItemTableViewCell 
    let product = productsToDisplay[indexPath.row] 
    cell.nameLabel.text = product.name // change that to the real property in SKProduct 
    return cell 

} 
+0

非常感謝你! – David

0

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell不應由系統直到你的異步加載調用完成調用。

您必須執行func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int並讓它返回productsToDisplay中的元素數。那麼系統只有在至少有一行顯示時纔會調用cellForRowAt indexPath

當您的異步請求完成時,切記在tableView上調用reloadData

相關問題