Wonjae Oh
Wonjae Oh

Reputation: 33

What's the syntax for updating existing attributes in core data compared to saving a new object in core data?

How is the syntax for adding new data to core data different from updating existing data in core data. For instance, if I have a core data entity of Person and attributes name: String, gender: String, and last_occupation: [Int : String](where Int corresponds to their age when they quit), I am confused which of the two syntax I already know I should use.

let appDelegate = UIApplication.shared.delegate as? AppDelegate
let context = appDelegate.persistentContainer.viewContext
let container = NSEntityDescription.insertNewObject(forEntityName: "Person", into: context) as! Person

//And then assigning attributes

container.name = some_string
container.gender = some_string
container.last_occupation = custom_object_that_conformsTo_codable_protocol

VS

let fetchRequest = NSFetchRequest(entityName: "Person")
let results = try context.fetch(fetchRequest)
if let container = results.first {
   container.name.value = some_string
   container.gender.value = some_string
   container.last_occupation = custom_object
   try context.save()
   context.refresh(transformableContainer, mergeChanges: false)
}

When should I use one method over another, and if I know that I will be replacing existing attributes in core data with newly updated ones instead of just changing their values, is it okay to use the first method?

Upvotes: 0

Views: 943

Answers (1)

vadian
vadian

Reputation: 285150

  • The first syntax inserts a new record – you have to save the context afterwards.

  • The second syntax fetches existing data and updates a record.

However to update a specific record you have to add a predicate and most likely you don't want to update the name and the gender attributes

let name = "John Doe"
let fetchRequest : NSFetchRequest<Person> = Person.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "name == %@", name)
let results = try context.fetch(fetchRequest)
if let container = results.first {
   // container.name = some_string
   // container.gender = some_string
   container.last_occupation = custom_object
   try context.save()
   context.refresh(transformableContainer, mergeChanges: false)
}

Upvotes: 3

Related Questions