为什么tableviewcell返回一个可选的(“”)

问题描述 投票:0回答:2

我试图将我的请求结果从api显示到一个单元格中。我能够发出请求并解析数据。但是当我尝试在单元格中显示内容并打印单元格值时,结果是可选的(“”)。有人可以解释为什么。

cell.restaurantNameLabel.text = apiDataModel.restaurantName

apiDataModel.restaurantName不是nil

任何帮助表示赞赏!谢谢

override func tableView(_ tableView: UITableView, cellForRowAt  indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! DiscoverTableViewCell

    cell.discoverImage.image = UIImage(named: "Detail")
    cell.restaurantNameLabel.text = apiDataModel.restaurantName


    return cell
}


override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
      let currentCell = tableView.cellForRow(at: indexPath) as! DiscoverTableViewCell
         print(currentCell.restaurantNameLabel.text)


}

func search(url: String, parameters : [String:String]) {
    let headers: HTTPHeaders = ["Authorization":"Bearer \(apiKey)"]
    Alamofire.request(url, method: .get, parameters: parameters, headers: headers ) .responseJSON{
        URLResponse in
        //print(URLResponse)
        if URLResponse.result.isSuccess {
            let yelpDataJSON = JSON(URLResponse.value!)
            self.updateYelpData(Json: yelpDataJSON)
            print("\(yelpDataJSON)")
        }else{
            print("error")
        }

    }
}

func updateYelpData(Json : JSON){

   if  let nameJSON = Json["businesses"][0]["name"].string {

   apiDataModel.restaurantName = nameJSON
    print(apiDataModel.restaurantName)
    apiDataModel.restaurantLocation = Json["businesses"][0]["location"]["display_address"][0].stringValue


    }else{
        print("error")
    }
}
ios swift uitableview tableview
2个回答
2
投票

您没有向我们展示您调用search的位置,但request是一种异步方法,但您永远不会在reloadData的桌面视图中调用updateYelpData。因此,表视图的初始填充是在Alamofire检索和解析数据之前发生的。

如果你将tableView.reloadData()放在updateYelpData中,表格视图将在Alamofire检索后用真实数据更新。


1
投票

它似乎apiDataModel.restaurantNamenil / ""并设置标签文本将使它""

你需要重新加载表

self.updateYelpData(Json: yelpDataJSON)
self.tableView.reloadData()

并确保您有一个有效的结果

© www.soinside.com 2019 - 2024. All rights reserved.