2021年4月24日星期六

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?

https://stackoverflow.com/questions/67249602/whats-the-syntax-for-updating-existing-attributes-in-core-data-compared-to-savi April 25, 2021 at 11:50AM

没有评论:

发表评论