UITableView未从API调用加载数据



在我的代码中,我有一个搜索栏,当它的搜索按钮被点击时,它会在这里触发这个功能:

func getStocks(ticker: String) {
        do {
            try Stocks.getStocks(ticker, completion: {stockList in
                self.listOfStocks = stockList
                print("Stock item is: n", self.listOfStocks.popLast())
                dispatch_async(dispatch_get_main_queue(), {
                    self.saveStocks(self.listOfStocks.popLast()!)
                    self.tableView.reloadData()
                })
            })
            } catch {
                print("Failed to get stocks")
        }
    }

此函数的目的是通过我的API调用,获取用户在搜索栏中指定的项目的数据,将其附加到全局项目列表中,同时将全局列表中的最新项目保存到核心数据中。稍后,我有一个代码块,用于设置文本单元格标签,并将其设置为Stock结构的名称属性:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("stockItem", forIndexPath: indexPath)
    if let label:UILabel = cell.textLabel {
        label.text = self.listOfStocks[indexPath.row].name
    }
    return cell
}

我已经检查过以确保重用标识符是正确的,这样就不会出现问题。

您首先需要找出代码中的问题所在。我会按照这些步骤去做。

  1. 确认Stocks.getStocks()静态函数工作正常,并且api调用返回有效数据。您尚未为此提供代码。

  2. 检查您的数据源(在本例中为self.listOfStocks)是否使用API调用的数据填充。在getStocks()方法中设置断点或使用print语句。

`

func getStocks(ticker: String) {
        do {
            try Stocks.getStocks(ticker, completion: {stockList in
                if let list = stockList {
                    self.listOfStocks = list
                    dispatch_async(dispatch_get_main_queue(), {
                        if let last = self.listOfStocks.popLast() {
                            self.saveStocks(last)
                        }
                        self.tableView.reloadData()
                    })
                } else {
                    print("ERROR: stockList is nil!")
                }
            })
            } catch {
                print("Failed to get stocks")
        }
   }
  1. 检查表视图委派和dataSource委派方法是否正确设置。下面是我如何检查cellForRowAtIndexPath方法。

    override func tableView(tableView:UITableView,cellForRowAtIndexPath indexPath:NSIndexPath)->UITableViewCell{let cell=tableView.dequeueReusableCellWithIdentifier("stockItem",forIndexPath:indexPath)

    if let datasource = self.listOfStocks[indexPath.row] {
        textLabel.text = datSource.name
    } else {
        textLabel.text = "Row (indexPath.row): NOT set!"
    }
    return cell 
    

    }

最新更新