首页 > 解决方案 > 为什么 tableviewcell 返回一个 optional("")

问题描述

我正在尝试将我的请求结果从 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")
    }
}

标签: iosswiftuitableviewtableview

解决方案


您没有向我们展示您调用的位置search,而是request一个异步方法,但您从不调用reloadData内部的表视图updateYelpData。因此,表格视图的初始填充发生在 Alamofire 检索和解析数据之前。

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


推荐阅读