iOS Core Data when to save context? iOS Core Data when to save context? ios ios

iOS Core Data when to save context?


You don't have to save the context that early in the process, especially when you want to modify the object afterwards.

In most cases you should create a separate NSManagedObjectContext for the changes you're about to perform on the database. So create objects on it, fill out the properties needed, then send save and perform the whole mergeChangesFromContextDidSaveNotification: trick with the main context (most likely running on the main thread, so using performSelectorOnMainThread... message).

By default an object created and returned by NSManagedObjectContext is autoreleased. If you've created a new object and want to edit it in a form sheet for example, you can call setRetainsRegisteredObjects: with YES to the managed object context before creating the object, so it holds on to the object created until you're done with it. Remember that it's not recommended to manage the NSManagedObjects' lifecycle on your own - you should let the NSManagedObjectContext do it. So, having that in mind, you don't have to retain the NSManagedObject. After the save operation it's unregistered by the context and removed from memory. Nothing is required on your side.

Answer to updated question part

It would be probably better if you returned an NSManagedObjectID (using [object objectID]) instead of the object itself. It allows to safely dispose of the object by the context and if one needs the object for further editing or data retrieval (e.g. from other contexts), they can fetch it from the store separately.

Even if you don't save the context, the newly created object is there and then you can decide if you want to keep the object or not.

After saving on the other hand, if the context still exists, it may return the object with given NSManagedObjectID to you from memory cache - without touching the database.

On yet another hand ;), in your case, you can pretty much safely return the object, since the NSManagedObjectContext creating it still exists, so the object will still exist as well, although already in the autorelease pool.