如何在Parse中存储计数器变量

时间:2015-11-03 17:52:22

标签: ios swift parse-platform counter

以下是我的代码。我有3个变量(likeCountdislikeCountVote),我需要在课程中存储"喜欢"。我还有一个用户指针,并在课堂上发布"喜欢"。我该如何存储这些变量?谢谢!

表视图控制器:

class UserFeedTableViewController: PFQueryTableViewController {
    var shouldReloadOnAppear: Bool = true

    // Votes: -1 for dislike, 1 for like, 0 for no vote
    var vote: Int = 0 // initialize to user's existing vote, retrieved from the server
    var likeCount: Int = 0 // initialize to existing like count, retrieved from the server
    var dislikeCount: Int = 0 // initialize to existing dislike count, retrieved from the server

    @IBAction func dislikeButton(sender: UIButton) {

    buttonWasClickedForVote(-1)

    self.tableView.reloadData()
    print(likeCount)
    print(dislikeCount)
}

@IBAction func likeButton(sender: UIButton) {

    buttonWasClickedForVote(1)

    self.tableView.reloadData()
    print(likeCount)
    print(dislikeCount)      
}

private func buttonWasClickedForVote(buttonVote: Int) {
    if buttonVote == vote {
        // User wants to undo her existing vote.
        applyChange(-1, toCountForVote: vote)
        vote = 0
    }
    else {
        // User wants to force vote to toggledVote.
        // Undo current vote, if any.
        applyChange(-1, toCountForVote: vote)

        // Apply new vote.
        vote = buttonVote
        applyChange(1, toCountForVote: vote)
    }
}

private func applyChange(change: Int, toCountForVote vote: Int ) {
    if vote == -1 { dislikeCount += change }
    else if vote == 1 { likeCount += change }
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath      indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell? {
    let CellIdentifier = "Cell"

    var cell: UserFeedCell? = tableView.dequeueReusableCellWithIdentifier(CellIdentifier, forIndexPath: indexPath) as? UserFeedCell

    if cell == nil {
        cell = UserFeedCell(style: UITableViewCellStyle.Default, reuseIdentifier: CellIdentifier)

    }

    if object != nil {
        cell!.likeButton.selected = vote == 1

        cell!.dislikeButton.selected = vote == -1
        cell!.likeButton.setTitle("\(likeCount)", forState: .Normal)
        cell!.dislikeButton.setTitle("\(dislikeCount)", forState: .Normal)

        }

    return cell
}

表视图单元格:

class UserFeedCell: PFTableViewCell {

    @IBOutlet weak var likeButton: UIButton!

    @IBOutlet weak var dislikeButton: UIButton!

    var post: PFObject? {
        didSet{   
        }
    } 
}

1 个答案:

答案 0 :(得分:0)

创建类“Like”的PFObject,并使用PFObject增量方法将它们更改适当的量,然后保存对象。