Reputation: 5559
I have a parse.com backend. I have a Message class which is a subclass of PFObject. I store the messages from the db in an array messages = Message.
Im having trouble when I need to update the records as Im getting duplicates.
What I've been trying to do is get a message from the messages array and then call saveInBackgroundWithBlock... thinking the backend will know its referring to an existing row in the db.
I've also just come across fetchIfNeeded.
My code is below. Where am I going wrong? How should I update existing records that are stored locally in an array of messages. How should I be using fetchIfNeeded in my scenario, if at all? Or should I be using core data / local storage in some way? (confused)
class Message : PFObject, PFSubclassing {
var messageTitle : NSString
var imageFile: PFFile
}
func getMessages() {}
var currentMessages = [Message]()
var messageQuery = Message.query()
messageQuery.findObjectsInBackgroundWithBlock { (objects: [AnyObject]!, error: NSError!) -> Void in
for object in objects {
var message = Message()
message.messageTitle = object["messageTitle"] as String
message.imageFile = object["imageFile"] as PFFile
self.currentMessages.append(message)
}
}
func updateMessage() {
message.messageTitle = self.messageTitle.text
let imageData = UIImagePNGRepresentation(self.imageToPost.image)
let imageFile = PFFile(name: "image.png", data: imageData)
message.imageFile = imageFile
message.saveInBackgroundWithBlock({ (success: Bool!, error: NSError!) -> Void in
if success == false {
self.displayAlert("Something went wrong", error: "Please try again later")
} else {
self.navigationController?.popViewControllerAnimated(true)
}
})
}
func saveNewMessage() {
message = Message()
message.messageTitle = messageTitle.text
let imageData = UIImagePNGRepresentation(self.imageToPost.image)
let imageFile = PFFile(name: "image.png", data: imageData)
message.imageFile = imageFile
message.saveInBackgroundWithBlock({ (success: Bool!, error: NSError!) -> Void in
if success == false {
self.displayAlert("Something went wrong", error: "Please try again later")
} else {
self.navigationController?.popViewControllerAnimated(true)
}
})
}
Upvotes: 0
Views: 216
Reputation: 11598
The reason you're seeing this error is that you are creating new Message
objects in your completion block rather than using the object that's been returned by the query.
func getMessages() {
var currentMessages = [Message]()
var messageQuery = Message.query()
messageQuery.findObjectsInBackgroundWithBlock { (objects: [AnyObject]!, error: NSError!) -> Void in
for object in objects {
// This is now creating a new, unsaved "Message" object
var message = Message()
message.messageTitle = object["messageTitle"] as String
message.imageFile = object["imageFile"] as PFFile
self.currentMessages.append(message)
// This might be a much easier way to do what you want:
self.currentMessages = objects
}
}
}
Upvotes: 1