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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With