Reputation: 4580
Maybe this question is very basic but I am looking for a nice way to decrement a value. I have a column called "credit" in _User table. Default value is 0. I want to decrement one credit from this column. This is what I have so far:
//Decrement user credit
let query2 = PFQuery(className:"_User")
query2.whereKey("user", equalTo: PFUser.currentUser()!)
query2.getFirstObjectInBackgroundWithBlock {
(object: PFObject?, error: NSError?) -> Void in
if error != nil
{
PFUser.currentUser()!["credit"] = (PFUser.currentUser()!["credit"] as! Int) - 1
self.navigationController?.popViewControllerAnimated(true)
}
}
Upvotes: 1
Views: 611
Reputation: 2330
object.decrementKey("key", byAmount: myIntValue)
has been removed from Parse SDK methods (at least with iOS). The doc isn't up-to-date anymore.
You can now decrement by incrementing with a negative value, like this :
object.incrementKey("key", byAmount: NSNumber(value: -1 * myIntValue))
Upvotes: 1
Reputation: 2316
To decrement, and also increment, a particular field, Parse has some built-in methods:
object.incrementKey("key")
object.incrementKey("key", byAmount: 2) // any int amount
object.decrementKey("key")
object.decrementKey("key", byAmount: 2) // any int amount
So after fetching your user object in that query, your code will become:
PFUser.currentUser().incrementKey("credit")
PFUser.currentUser().saveInBackgroundWithBlock {
(success: Bool, error: NSError?) -> Void in
if (success) {
// The credit key has been incremented
} else {
// There was a problem, check error.description
}
}
See Parse documentation here on Counters.
Upvotes: 1