Search code examples
iosswiftcore-data

CoreData save some changes from child Managed Object Context?


I want to create temporary managed objects and save/discard them conditionally.

The consensus seems to be that I should create a child managed object context and conditionally save/discard it.

In that case, how do I persist one of the temporary entities and discard the rest?


Solution

  • Temporary NSManagedObject instances do not need to be associated with a context.

    In your situation, create the instances without a context. Pass nil into the instance on creation instead of a child context.

    When you are ready to save one of those objects, give it a context and call save on that context.

    Reading the comments above, a struct works if you have a high ratio of discard to save. If the situation is reversed (mostly saves) then I would load into MOs and discard. Memory and performance will be the drivers for you.