2017-03-31 54 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

相关问题