-1

In my entity i have 5 attributes and some values are already saved, i cannot search specific value from saved data and update the data and save it.

Data 1

name = Conc;
url = "http://192.168.1.12/snapshot";
ipaddress = "http://192.168.1.102";
pass = we;
prof = "Profile_1";
user = web;

Data 2

name = P1;
url = "http://192.168.1.150/hello";
ipaddress = "http://192.168.1.112";
pass = hello;
prof = "Profile_1";
user = web;

All this is saved in my core data i wanted to search the name P1 and replace the data which user adds into the text field and update it.

but it adds as a new entry into the core data.

code used to save the data:

var coreDataIpAddress: [NSManagedObject] = []


guard let appDelegate =
        UIApplication.shared.delegate as? AppDelegate else {
            return
    }

    // 1
    let managedContext =
        appDelegate.persistentContainer.viewContext

    // 2
    let entity =
        NSEntityDescription.entity(forEntityName: "Data",
                                   in: managedContext)!

    let Data = NSManagedObject(entity: entity,
                                 insertInto: managedContext)

    // 3
    cameraData.setValue(ipAddress, forKey: "ipaddress")
    cameraData.setValue(snapshotUrl, forKey: "url")
    cameraData.setValue(cameraName, forKey: "name")
    cameraData.setValue(userName, forKey: "user")
    cameraData.setValue(password, forKey: "pass")
    cameraData.setValue(profileToken, forKey: "prof")


    // 4
    do {
        try managedContext.save()
        saveCameraDetails.append(Data)
    } catch let error as NSError {
        print("Could not save. \(error), \(error.userInfo)")
    }
}
  • You are inserting an entity without checking whether its present or not. Go through this : https://stackoverflow.com/questions/26345189/how-do-you-update-a-coredata-entry-that-has-already-been-saved-in-swift – Pallavi Srikhakollu Jan 17 '18 at 11:34
  • I have already checked the link but the answer is in Obj-c and not in swift. – Allison Rose Jan 18 '18 at 02:58

1 Answers1

0

Every time this line of code executes:

let Data = NSManagedObject(entity: entity,
                             insertInto: managedContext)

...you are telling Core Data to create a new instance. That's why you get new entries, because you keep creating them. If you want to update an existing instance, you need to get the existing instance instead of creating a new one. Usually you do this with an NSFetchRequest. Apple provides detailed documentation with sample code that explains this.

Tom Harrington
  • 69,312
  • 10
  • 146
  • 170