在我的应用中我试图在每次创建活动时给用户点数。我正在设置一个PFQuery来检索当前分数,然后将所需的点数保存回课堂。我的问题是,一旦创建了分数,我就无法更新分数,所以我需要一种方法来更新"添加得分的当前得分数据 这是我的代码:
// Give the User Points
let saveScore = PFUser.currentUser()
var query = PFQuery(className:"User")
query.whereKey("score", equalTo: saveScore!)
query.findObjectsInBackgroundWithBlock ({
objects, error in
if error == nil {
// The find succeeded.
println("Successfully retrieved \(objects!.count) scores.")
// Do something with the found objects
if let objects = objects as? [PFObject] {
for object in objects {
let Score = object["score"] as! String
println(object.objectId)
let Points = ("100" + Score)
saveScore!.setObject(Points, forKey: "score")
saveScore!.saveInBackgroundWithBlock { (success: Bool,error: NSError?) -> Void in
println("Score added to User.");
}
}
}
} else {
// Log details of the failure
println("Error: \(error!) \(error!.userInfo!)")
}
})
有人可以帮忙吗? 感谢
答案 0 :(得分:1)
由于您已经拥有当前用户,因此没有理由对其进行查询。但是,如果需要,您应该获取它以确保您使用最新数据。获取后,设置您的分数变量,添加100个字符串,然后保存更新的分数变量,如下所示:
if let currentUser = PFUser.currentUser() {
currentUser.fetchIfNeededInBackgroundWithBlock({ (foundUser: PFObject?, error: NSError?) -> Void in
// Get and update score
if foundUser != nil {
let score = foundUser!["score"] as! String
let points = "100" + score
foundUser!["score"] = points
foundUser?.saveInBackgroundWithBlock({ (succeeded: Bool, error: NSError?) -> Void in
if succeeded {
println("score added to user")
}
})
}
})
}
答案 1 :(得分:0)
您需要查询已保存的对象,然后像平常一样保存。它会像这样更新:
var query = PFQuery(className:"GameScore")
query.getObjectInBackgroundWithId("xWMyZEGZ") {
(gameScore: PFObject?, error: NSError?) -> Void in
if error != nil {
println(error)
} else if let gameScore = gameScore {
gameScore["cheatMode"] = true
gameScore["score"] = 1338
gameScore.saveInBackground()
}
}