Best Practices for Updates

I am building an app leverage the CoreDataStack method described in the book, however when I show my user the appropriate entry and then allow them to go to an “Edit” screen to update the entry… it crashes on the and the error catch doesn’t seem to provide any details. Here’s the code I use to do the save…

` @IBAction func saveRecipient(_ sender: Any) {

    if let firstNameText = firstName.text {
        selectedRecipient = Recipient(context: managedContext)
        selectedRecipient?.firstName = firstNameText
        selectedRecipient?.lastName = lastName.text!
        selectedRecipient?.addressLine1 = addressLine1.text!.capitalized(with: NSLocale.current)
        selectedRecipient?.addressLine2 = addressLine2.text!.capitalized(with: NSLocale.current)
        selectedRecipient?.state = state.text!.uppercased()
        selectedRecipient?.city = city.text!.capitalized(with: NSLocale.current)
        selectedRecipient?.zip = zipCode.text!
        selectedRecipient?.country = country.text!.capitalized(with: NSLocale.current)
    do {
    } catch let error as NSError {
        print("Save error: \(error), \(error.userInfo)")
    navigationController?.popViewController(animated: true)


What is the best practice for doing a entry update?

@theapapp Thanks very much for your question!

Have you used breakpoints to see where your code crashes? Also, can you post the error message that you are receiving from Xcode?

Ok, I figure it out… Dumb mistake… I had copied the view controller from my add controller and the Save button was not running the right code… however now when the is executed… it actually creates a new entry, instead of updating the existing entry. How do I make it do an in place update instead of saving a new entry?

The above line is telling it make a new Recipient object, using the specified context.
If you want to edit one, you would need to set selectedRecipient to the object when you open the view, then apply the property updates to that, and save it in the same way.

If you move the above line out, and then either pass in an existing object, or create a new one, you can make the saveRecipient method work for both cases.

1 Like

Thanks @sgerrard Just removed the line and it worked perfectly (problem with cut and paste of my add function…

This topic was automatically closed after 166 days. New replies are no longer allowed.