ios - 为什么 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")
}
}
解决方案
您没有向我们展示您调用的位置search
,而是request
一个异步方法,但您从不调用reloadData
内部的表视图updateYelpData
。因此,表格视图的初始填充发生在 Alamofire 检索和解析数据之前。
如果你放一个tableView.reloadData()
inside updateYelpData
,表格视图将在被 Alamofire 检索后用真实数据更新。
推荐阅读
- javascript - JS 正则表达式正面向后看不匹配
- kotlin - 如何从活动中访问数据类对象?
- jenkins - Jenkins - 在同一视图中显示多个多分支管道的所有主分支
- android - 如何使用带有颤振的 agora 实现语音通话?
- python - 如何在另一个列表中查找列表项?
- javascript - UnhandledPromiseRejectionWarning:ValidationError:file validatiofailed:uuid:Cast to Number failedfor value"dc1-c7ffd748df"(type string) at path"uuid
- android - 如何先加载活动?
- c# - 如何让 ScrollView 的 Scrolled 事件只响应 Xamarin.Forms 中的用户操作?
- javascript - 是否可以将类更改应用于 d3.js 中的 selection.classed() 元素,或者设置相对于其 currentValue 的 CSS 属性值
- math - Genshin Impact box 谜题 - 数学建模和潜在方法