为什么tableviewcell返回一个optional(“”)

时间:2019-04-13 16:39:16

标签: ios swift uitableview tableview

我试图将来自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")
    }
}

2 个答案:

答案 0 :(得分:2)

您没有向我们显示您在何处调用search,但是request是一种异步方法,但是您从未在reloadData内的表视图上调用updateYelpData。因此,在Alamofire检索和解析数据之前,就发生了表视图的初始填充。

如果您将tableView.reloadData()放在updateYelpData内,则Alamofire检索后,表视图将使用真实数据进行更新。

答案 1 :(得分:1)

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

您需要在之后重新加载表格

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

并确保您获得有效结果