0

My app sometimes inserts objects into the managed object context that are not meant to necessarily be saved. For example, when I launch an 'add entity' modal, I create a managed object and assign it to the modal. If the user saves from that modal, I save the context. If he cancels, I delete the object and no save is necessary.

I have now introduced an 'import' feature that switches to my app (using a URL scheme) and adds an entity. Because one of these modals might be open, it is not safe to save the context at this point. The transient object created for the modal will be saved, even if the user cancels, and there is no guarantee that the deletion (from the cancel operation) will be saved later - the user might quit the app.

Similarly, I can't simply save whenever my app quits. If the modal is open at that point, the temporary object will be incorrectly saved.

I am looking for a strategy to handle this architecture. I am considering some 'flagging' solution that allows me to identify the imported entities. When the user user quits the app, I will check if there are any unsaved changes to the context. If so, I will filter out everything except the imported entities, and then save. I have no idea if this is possible (selective saving) or a good idea.

Ben Packard
  • 26,102
  • 25
  • 102
  • 183
  • 1
    Sounds like your modal should be using a separate context, which will allow you to save the main context without accidentally picking up in-progress changes from the modal. – Lily Ballard Jan 10 '13 at 00:13
  • 1
    Great article here: http://www.cocoanetics.com/2012/07/multi-context-coredata/ on using child contexts for different scanarios including the one you've described. – Andrew Tetlaw Jan 10 '13 at 00:35
  • Thanks guys - I've read the linked blog a few times and am attempting an implementation. I have some issues but it feels like the right path so far. I will add my own answer detailing my solution when it is working. – Ben Packard Jan 11 '13 at 17:50
  • These are my (current) outstanding concerns: http://stackoverflow.com/questions/14284301/using-a-child-nsmanagedobjectcontext-for-displaying-a-modal – Ben Packard Jan 11 '13 at 18:21

1 Answers1

0

Kevin and Andrew's comments (and the linked article) were enough to get me going. I got some follow-up advice in this question.

In summary, I am using a child context to create the transient object, and then merging it into the main context. In effect, I only need the temporary context as place to insert the object - if it was possible, for example, to create it outside of an insert message, I could do so and then insert it straight into the main context on confirmation.

Community
  • 1
  • 1
Ben Packard
  • 26,102
  • 25
  • 102
  • 183