我正在尝试制作一个社交媒体应用程序,功能之一是点赞按钮,不幸的是,当您单击所有功能时,一切正常,但始终无法正确更新点赞和点赞按钮的次数。我认为这与刷新有关,但是我需要刷新它才能更新喜欢的数量。有人知道发生了什么吗...
func like(sender: AnyObject) {
var buttonPosition: CGPoint = sender.convertPoint(CGPointZero, toView: self.table)
var indexPath: NSIndexPath = self.table.indexPathForRowAtPoint(buttonPosition)!
if sender.currentTitle == "Like" {
sender.setTitle("Unlike", forState: .Normal)
var addLikeQuery = PFQuery(className: "Post")
addLikeQuery.whereKey("message", equalTo: self.messages[indexPath.row])
addLikeQuery.findObjectsInBackgroundWithBlock { (aPosts, error) -> Void in
if let aPosts = aPosts {
for aPost in aPosts {
aPost.addUniqueObject(PFUser.currentUser()!.objectId!, forKey: "likers")
self.likeDisplayText = ((aPost["likers"] as! [String]).count - 1).description + " Like"
self.table.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .None)
aPost.saveInBackgroundWithBlock({ (success, error) -> Void in
if error != nil {
self.likeDisplayText = "Couldn't Like Picture!"
}
})
}
}
}
} else {
sender.setTitle("Like", forState: .Normal)
var removeLikeQuery = PFQuery(className: "Post")
removeLikeQuery.whereKey("message", equalTo: self.messages[indexPath.row])
removeLikeQuery.findObjectsInBackgroundWithBlock { (rPosts, error) -> Void in
if let rPosts = rPosts {
for rPost in rPosts {
rPost.removeObject(PFUser.currentUser()!.objectId!, forKey: "likers")
self.likeDisplayText = ((rPost["likers"] as! [String]).count - 1).description + " Like"
self.table.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .None)
rPost.saveInBackgroundWithBlock({ (success, error) -> Void in
if error != nil {
self.likeDisplayText = "Couldn't Like Picture!"
}
})
}
}
}
}
}
最佳答案
我不确定您的问题是什么,但我可能有一些见识。如果您试图通过执行大量处理或在另一个线程中的函数来编辑UI中的某些元素,建议将其设置为Asynchronus,并在要编辑UI的该函数中的任何位置使该代码在主线程上运行。这就是我的意思。
func like(sender: AnyObject) {
dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.value), 0)) {
// do background stuff
dispatch_async(dispatch_get_main_queue()) {
// when you want to edit the text of the button
// or change something in your UI
// do it in here
self.likeDisplayText = "Couldn't Like Picture!"
}
}
}