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.
Remove inserted but unsaved object from Core Data Managed Object Context
Asked Answered
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
© 2022 - 2024 — McMap. All rights reserved.