mirror of
https://github.com/JohnEstropia/CoreStore.git
synced 2026-01-11 20:00:30 +01:00
Pattern for editing a model object #30
Reference in New Issue
Block a user
Delete Branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Originally created by @markkrenek on GitHub (Jan 6, 2016).
What's the suggested pattern for editing an NSManagedObject in a cancelable view controller? View controller A displays a list of model objects. The user selects one and then view controller B is displayed for editing the object. In pure Core Data, I pass the object to B, it creates its own child MOC, and performs edits on the object in that context. If the user cancels, the MOC is allowed to be released and no changes are saved. If the user presses Save, the child MOC is saved, and recursively saves until committed to the store.
(This is the pattern I've used in the past, where I directly edit an NSManagedObject in a temporary MOC as the user makes changes. The alternative is to maintain the edited values in local vars of the view controller and then push those changes onto the NSManagedObject only when the user presses Save. I find the former to be easier when edits might have ripple effects through relationships or computed values.)
@JohnEstropia commented on GitHub (Jan 7, 2016):
@markkrenek This is exactly the use-case that
UnsafeDataTransactions were designed for:If you want to cancel changes, just don't call
commit()on the transaction.@markkrenek commented on GitHub (Jan 7, 2016):
Thanks. I'm still wrapping my head around some of the abstraction that CoreStore is providing. I had not thought to use UnsafeDataTransaction simply because of the "Unsafe" name. It sounds like as long as I make changes to the object only from the main thread, I'll be OK.
@JohnEstropia commented on GitHub (Jan 7, 2016):
All transactions create their own temporary MOC and UnsafeDataTransaction lets you use it from any thread/queue. It's named "unsafe" because CoreStore cannot track changes made concurrently from other transactions. If your app does not update objects in the background then it should be fine.
Just make sure that you do not interact objects fetched/created from different contexts.
For example, don't do this:
You'll need to do this:
@markst commented on GitHub (Oct 25, 2018):
Hey @markkrenek. I hope it's alright to piggyback off your previous question!
I've a similar pattern to you with regard to having a cancelable view controller.
Let's say I reuse a view controller which can both create & edit a 'customer' details.
I'd like to know how you handle logic for creating the Customer model object on creation & if updating a previous object?
Here's what I have currently, any input much appreciated! :