I\'m not sure what I\'m doing wrong here, but when I save the first time into coredata, it works just fine. When I try to overwrite that, it doesn\'t.
func t
#Update Data in #CoreData #iOS #swift
Simply follow below steps to update data in CoreData which you already saved
#Step1 :- refer to persistent container & create object of viewContext
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let viewContext = appDelegate.persistentContainer.viewContext
#Step2 :- create FetchRequest
let fetchRequest = NSFetchRequest(entityName: "User") // here User is entity name
//Step3 :- add predicate to fetch request by passing attribute and value
fetchRequest.predicate = NSPredicate(formate: "userName = %@","XYZ")
//Step4 :- fetch record using viewContext by passing fetchRequest and set new value in it
do {
let results = try viewContext.fetch(fetchRequest) as? [NSManagedObject]
if result?.count !=0 {
result?[0].setValue("ABC",forKey: "userName")
}
} catch {
print("failed to fetch record from CoreData")
}
//Step5 :- finally call save method of viewcontext so new value get reflect in CoreData
do {
viewContext.save()
} catch {}
Note :- in predicate the value "XYZ" can be value of attribute and format will contain name of attribute such like username , age password ....etc , in result?[0].setValue you can set new value for particular attribute by passing value and keynote , you can skip step5 and can execute save method inside step4 after Line where we setting new value