如何立即更新swift上的数据

时间:2015-08-18 05:49:51

标签: swift uitableview reload alamofire

我想在按下“喜欢”按钮后立即在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
}

1 个答案:

答案 0 :(得分:2)

UI只应从main thread更新:

dispatch_async(dispatch_get_main_queue()) {
    self.tableView.reloadData()
}