Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove inserted but unsaved object from Core Data Managed Object Context

Is there a way to remove a single managed object which has already been inserted into a context but not yet saved? I want to remove a single object, not rollback the whole context. I've tried calling deleteObject: but it throws an exception since, according to core data, the object doesn't exist in the MOC yet. By looking at core data's inserted objects property I definitely know that it has been inserted and by looking at deleted objects I know that it has been marked for deletion. Essentially I want to "uninsert" the object. Saving first then deleting is not acceptable. Thanks.

like image 267
paulbramsen Avatar asked Jul 02 '14 18:07

paulbramsen


People also ask

How do I delete an object in Core Data?

Table views have a built-in swipe to delete mechanic that we can draw upon to let users delete commits in our app. Helpfully, managed object context has a matching delete() method that will delete any object regardless of its type or location in the object graph.

What is managed object context in Core Data?

A managed object context represents a single object space, or scratch pad, in a Core Data application. A managed object context is an instance of NSManagedObjectContext . Its primary responsibility is to manage a collection of managed objects.

Can we have multiple managed object contexts in Core Data?

Most apps need just a single managed object context. The default configuration in most Core Data apps is a single managed object context associated with the main queue. Multiple managed object contexts make your apps harder to debug; it's not something you'd use in every app, in every situation.

Will you ever pass Managedobject from one context to another context?

You cannot pass NSManagedObjects between multiple contexts, but you can pass NSManagedObjectIDs and use them to query the appropriate context for the object represented by that ID.


1 Answers

It turns out that it is totally legal to call deleteObject: on an object that has not yet been persisted. According to Apple's documentation:

If object has not yet been saved to a persistent store, it is simply removed from the receiver.

My problem was actually a result of the fact that there was a retain cycle due to the managed object's relationships. This was solved by setting the problematic relationships to nil.

Note: until you save the MOC the managed object that you just inserted then deleted will appear in both MOC.insertedObjects and MOC.deletedObjects

like image 52
paulbramsen Avatar answered Sep 22 '22 14:09

paulbramsen