Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use the save: method of NSManagedObjectContext

The question is quite simple: when should I use the save:(NSError **)error method of NSManagedObjectContext? From what I understand the only thing it does it save changed data to the persistent store. The Xcode template-generated application delegate calls the save: method on applicationWillTerminate, is that sufficient?

Details about my code:

  • Multi-threaded (doing operations in the background, thus using multiple NSManagedObjectContext's)
  • I'm using a single NSPersistentStoreCoordinator
  • Data changed on background threads is merged using mergeChangesFromContextDidSaveNotification:
  • If you need to know more, please do ask!

I couldn't find a guideline on when to call it, so I decided to ask you all. Thanks in advance for your replies!

like image 387
Koen Avatar asked Jul 31 '11 00:07

Koen


1 Answers

You always need to call save: when you want your data to save. You can't always guarantee that applicationWillTerminate will be called. For example, if your application crashes due to memory issues (or due to one of a handful of other things) then this won't be called.

I would save data when the user completes the action that is actually generating the data to save.

like image 155
dtuckernet Avatar answered Oct 20 '22 12:10

dtuckernet