3

I am new in core data. i just want to check if a record exists in core data then update else insert. i can insert, fetch delete data but unable to update. Here is my piece of code

var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
var user = [Users]()
func insertData() {

    let newUser = NSEntityDescription.insertNewObject(forEntityName: "Users", into: context)//entity(forEntityName: "Users", in: context)
    newUser.setValue("chatt", forKey: "name")
    newUser.setValue("100", forKey: "balance")
    newUser.setValue("123", forKey: "user_id")
    do {

        try context.save()

    } catch {

        print("Failed saving")
    } 
}

Please help me with the update code snippet

Dawid Wysakowicz
  • 3,334
  • 17
  • 33
Gorib Developer
  • 527
  • 2
  • 12
  • 27
  • https://stackoverflow.com/a/38459233/5461400 – Harshal Valanda Mar 26 '18 at 07:39
  • You can reference my answer [here](https://stackoverflow.com/a/48089530/4079505) – Devbot10 Oct 01 '18 at 19:04
  • This has been incorrectly moderated - if it's a duplicate, please cite the duplicated answers. Devbot10's answer is an answer to a different question - how to update a previously existing core data object - that's not the answer to this question. – Nostradamus May 12 '19 at 18:47

1 Answers1

5

try this :

var fetchRequest = NSFetchRequest(entityName: "Users")
fetchRequest.predicate = NSPredicate(format: "userName = %@", userName)

if let fetchResults = appDel.managedObjectContext!.executeFetchRequest(fetchRequest, error: nil) as? [NSManagedObject] {
    if fetchResults.count != 0 {
        // update
        var managedObject = fetchResults[0]
        managedObject.setValue(accessToken, forKey: "accessToken")

        context.save(nil)
    } else {
        //insert as new data
    }
}

Cheers :)

Jon Winstanley
  • 22,404
  • 20
  • 73
  • 111
Wendra
  • 479
  • 5
  • 7