如何立即更新 swift 上的数据
How to update data on swift immediately
我想在按下赞按钮后立即更新 swift 上的 likeNum 数据。在下面的 tapLike 函数中,我在服务器端更新了 likeNum 数据(由 rails 编写),然后通过 self.tableView.reloadData() 重新加载数据。但是,它不能同时更新显示的数据。你能告诉我如何立即更新数据吗?
func tapLike(recognizer: UITapGestureRecognizer){
var userId = self.defaults.objectForKey("uid") as! Int
let parameters = [
"id": recognizer.view!.tag,
"user_id": userId
]
Alamofire.request(.POST, uri.answersApi + "/like", parameters: parameters, encoding: .JSON)
.responseJSON { (request, response, data, error) in
self.tableView.reloadData()
}
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("qaIdentifier", forIndexPath: indexPath) as! QATableViewCell
cell.likeNum.text = String(answers[indexPath.row].likeNum!)
return cell
}
UI
应该只从 main thread
更新:
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
我想在按下赞按钮后立即更新 swift 上的 likeNum 数据。在下面的 tapLike 函数中,我在服务器端更新了 likeNum 数据(由 rails 编写),然后通过 self.tableView.reloadData() 重新加载数据。但是,它不能同时更新显示的数据。你能告诉我如何立即更新数据吗?
func tapLike(recognizer: UITapGestureRecognizer){
var userId = self.defaults.objectForKey("uid") as! Int
let parameters = [
"id": recognizer.view!.tag,
"user_id": userId
]
Alamofire.request(.POST, uri.answersApi + "/like", parameters: parameters, encoding: .JSON)
.responseJSON { (request, response, data, error) in
self.tableView.reloadData()
}
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("qaIdentifier", forIndexPath: indexPath) as! QATableViewCell
cell.likeNum.text = String(answers[indexPath.row].likeNum!)
return cell
}
UI
应该只从 main thread
更新:
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}