我正在尝试为我的电影应用制作一些投票按钮。
我使用Parse,我创建了一个名为Votes_Up
的新类。在本课程中,他们分为两列:User_Voting
和Film_VotedFor
。
按下按钮时,下面的代码会被执行。它将当前用户和电影对象按下按钮,然后将它们添加到Parse。我的数据库如下所示:
我需要什么
所以他们当前的工作方式,如果用户按下投票按钮,它会将信息添加到数据库并将计数加1。当用户再次按下它时,它只是通过取消1来更新计数。
我还想删除它已经添加到数据库中的行,由投票给它的用户删除。我怎么能这样做?
我的代码:
@IBAction func upVoteButton(sender: UIButton) {
let hitPoint = sender.convertPoint(CGPointZero, toView: self.tableView)
let hitIndex = self.tableView.indexPathForRowAtPoint(hitPoint)
let object = objectAtIndexPath(hitIndex)
if PFUser.currentUser() != nil {
if userPressedUpButton == false {
userPressedUpButton = true
let voteUp = PFObject(className: "Votes_Up")
voteUp["User_Voting"] = PFUser.currentUser()
voteUp["Film_VotedFor"] = object!
object!.incrementKey("UpVoteCount")
object!.saveInBackground()
voteUp.saveInBackgroundWithBlock({ (success, error) in
if success == true {
// Object(s) was/were successfully saved
} else if error != nil {
// Display an alert to the user
} else {
// Display an alert to the user - something went wrong
}
})
} else {
userPressedUpButton = false
// I need to removed the row from the class here that was added, as the user has retracted their vote!
object!.incrementKey("UpVoteCount", byAmount: -1)
object!.saveInBackground()
}
} else {
// No user is logged in so they can't vote
performSegueWithIdentifier("Votes_LoginPopup", sender: self)
}
self.tableView.reloadData()
}
答案 0 :(得分:0)
试试这个:
var query = PFQuery(className:"Votes_Up")
query.whereKey("User_Voting", equalTo:PFUser.currentUser())
query.limit = 1
query.findObjectsInBackgroundWithBlock {
(votesUp: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
if let objects = votesUp as? [PFObject] {
var firstObject = objects[0]
dispatch_async(dispatch_get_main_queue(),{
// do delete here
firstObject.deleteEventually();
})
}
}
}
或者这个:
let query = PFQuery(className: "Votes_Up")
query.whereKey("User_Voting", equalTo: PFUser.currentUser())
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
for object in objects {
object.deleteEventually()
}
}