ios - 为什么 tableviewcell 返回一个可选的 ("")

标签 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")
    }
}

最佳答案

您没有向我们展示您在哪里调用了search,但是request 是一个异步方法,但是您从来没有在您的表上调用过reloadDataupdateYelpData 中查看。因此, TableView 的初始填充发生在 Alamofire 检索和解析数据之前。

如果在 updateYelpData 中放置一个 tableView.reloadData(),当 Alamofire 检索到真实数据后, TableView 将更新为真实数据。

关于ios - 为什么 tableviewcell 返回一个可选的 (""),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55667680/

相关文章:

ios - NSOperation 和 NSURLConnection 迷惑了

ios - 在 UIPresentationController 中动画呈现 View

ios - iOS5 Storyboard 中的 Compilation Failed 错误

ios - 在 cordova 3.5.0 中未调用离线和在线事件

ios - Firebase + 快速检索用户数据

swift - 索引 Metal 缓冲区的问题

ios - 带有 UISearchBar 作为标题 View 的 UITableView 导致崩溃

ios - CGAffineTransform 在 iOS 7 中进行旋转

ios - UITableViewCell 高度未在 StoryBoard 中设置

ios - 与 UITableView 具有相同背景的模糊导航栏