Steffen Myklebust
Steffen Myklebust

Reputation: 25

Core Data update code is duplicating records using Swift

I have a simple question regarding Swift Core Data update.

The following code creates new record for each save. WHY??? It should create new entry if there is no data in the User table, and if it has data update existing.

My User table should hold one record only

    @IBAction func btnSave(){

    var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
    var context:NSManagedObjectContext = appDel.managedObjectContext!

    var newUser = NSEntityDescription.insertNewObjectForEntityForName("User", inManagedObjectContext: context) as NSManagedObject

    var request = NSFetchRequest( entityName: "User")
    //    request.returnsObjectsAsFaults = false

    var results:NSArray = context.executeFetchRequest(request , error: nil)!

    //Upate the firste record
    if(results.count != 0 ){
    var res = results[0] as NSManagedObject
    res.setValue(firstName.text, forKey: "firstName")
    res.setValue(lastName.text, forKey: "lastName")
    res.setValue(address.text, forKey: "address")
    res.setValue(postal.text, forKey: "postal")
    res.setValue(city.text, forKey: "city")
    res.setValue(lblUUID.text, forKey: "savedUUID")

    lblUUID.text = String(results.count) // used for debug -- show numbers of records in array

    context.save(nil)

    println("Update")

    }else{
    // Create new record if array has nil records
    newUser.setValue(firstName.text, forKey: "firstName")
    newUser.setValue(lastName.text, forKey: "lastName")
    newUser.setValue(address.text, forKey: "address")
    newUser.setValue(postal.text, forKey: "postal")
    newUser.setValue(city.text, forKey: "city")
    newUser.setValue(lblUUID.text, forKey: "savedUUID")

    context.save(nil)

    println("New registration")
    }

Upvotes: 0

Views: 506

Answers (1)

salabaha
salabaha

Reputation: 2478

Before fetching and checking if user already exist you call this line of code:

 var newUser = NSEntityDescription.insertNewObjectForEntityForName("User", inManagedObjectContext: context) as NSManagedObject

which create new user each time you call btnSave().

So in order to fix this problem you need to move code above in to if else statement.

if(results.count != 0 ){
 ...
} else {
var newUser = NSEntityDescription.insertNewObjectForEntityForName("User", inManagedObjectContext: context) as NSManagedObject
...
}

And after this modification your code will work as expected.

Upvotes: 2

Related Questions