I have a button that pushes to a feed, I would like to record the name of the Feed Item in an array ("itemChosen") in my PFUser class every time the button is clicked:
@IBAction func buttonTapped(sender: UIButton) {
PFUser.currentUser()!.addObject(feedItem.feedItemName, forKey: "itemChosen")
PFUser.currentUser()!.saveInBackgroundWithBlock({ (success: Bool, error: NSError?) -> Void in
println(PFUser.currentUser()?.objectForKey("itemChosen"))
})
}
I get the error:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Operation is invalid after previous operation.'
If I use:
PFUser.currentUser()!.setObject(feedItem.feedItemName, forKey: "itemChosen")
I can save the name as a singular String, but I want to append it into an array. Why doesn't addObject work and how can I fix it?
Try doing this:
@IBAction func buttonTapped(sender: UIButton) {
if PFUser.currentUser()!["itemChosen"] == nil { PFUser.currentUser()!["itemChosen"] = [String]() }
(PFUser.currentUser()!["itemChosen"] as! NSMutableArray).addObject(feedItem.feedItemName)
PFUser.currentUser()!.saveInBackgroundWithBlock({ (success: Bool, error: NSError?) -> Void in
println(PFUser.currentUser()?.objectForKey("itemChosen"))
})
}
The problem is that PFUser.currentUser!["itemChosen"]
can be nil
.
Edit: I found a way to do it using Xcode 6:
extension PFUser {
var param: [String] {
get {
if let x = self["itemChosen"] as? [String] {
return x
} else {
return []
}
}
set(val) {
self["itemChosen"] = val
}
}
}
@IBAction func buttonTapped(sender: UIButton) {
PFUser.currentUser()!.param.append(feedItem.feedItemName)
PFUser.currentUser()!.saveInBackgroundWithBlock({ (success: Bool, error: NSError?) -> Void in
println(PFUser.currentUser()?.objectForKey("itemChosen"))
})
}