martin
martin

Reputation: 1974

Swift - Core data gets overwritten

I'm trying to save the properties from the messages that I'm sending, to my core data. But every time I'm saving new messages, they don't append the existing ones, they just overwrite the whole entity. I hope you understand what I mean.

My code looks like this, were my receivers are being retrieved from another VC:

    var receivers: [String] = []

        @IBAction func doneTapped(sender: AnyObject) {

            for receiver in receivers{

                var textMessage = PFObject(className:"textMessage")
                textMessage["Receiver"] = receiver
                textMessage["Message"] = messageOutl.text
                textMessage.saveInBackgroundWithBlock {

                    (success: Bool!, error: NSError!) -> Void in

                    if (success != nil) {

                        self.errorOccurred = true

                        NSLog("Object created with id: \(textMessage.objectId)")

                    } else {
                        NSLog("%@", error)
                    }
                }
            }
            let appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
            let contxt: NSManagedObjectContext = appDel.managedObjectContext!
            let en = NSEntityDescription.entityForName("MainTable", inManagedObjectContext: contxt)

            var newMessage = SecondModel(entity: en!, insertIntoManagedObjectContext: contxt)

            for rec in receivers{
                newMessage.receiver = rec
                newMessage.date = NSDate()
                newMessage.messageType = typeOfMessage
                contxt.save(nil)
            }
}

Any suggestions on how to solve this or why this happens would be appreciated.

EDIT: I changed my "en" and "newMessage" to this:

let en: AnyObject! = NSEntityDescription.insertNewObjectForEntityForName("MainTable", inManagedObjectContext: contxt)

var newMessage = SecondModel(entity: en! as NSEntityDescription, insertIntoManagedObjectContext: contxt)

but now I get an "(lldb)" error in the second line.

EDIT 2: I solved the issue by getting rid of the second for-loop and instead putting the "save-to-core-data" code in the first for-loop. I still don't know why the first code shouldn't work though.

Upvotes: 1

Views: 633

Answers (1)

trevorj
trevorj

Reputation: 2039

To insert into CoreData, you need to use

let en = NSEntityDescription.insertNewObjectForEntityForName( "MainTable", inManagedObjectContext: contxt) as YourType // If you have a custom type

when you create the entity.

Then you typically save with something like this:

var error: NSError?
if !contxt.save(&error) {
    println("Error: \(error)")
    abort() 
}

It looks like you're doing:

let en = NSEntityDescription.entityForName("MainTable", inManagedObjectContext: contxt)

to create the entity, but the entityForName:inManagedObjectContext: class method, according to the documentation, "Returns the entity with the specified name from the managed object model associated with the specified managed object context’s persistent store coordinator."

You don't want to get the object you've persisted; you want to create an object and persist it.

Hope it helps!

Upvotes: 4

Related Questions