Ben Packard
Ben Packard

Reputation: 26476

NSManagedObject is not deleted unless a fetch is requested

I am deleting a managed object from core data like this:

[item.managedObjectContext deleteObject:item];

(Note that this item is created, but not saved at this point.)

Trying to fix a bug, I wanted to confirm that the item was indeed deleted. First, since every 'item' belongs to a 'list', I logged the count of list.items before and after. There was no change. Suspect.

To be doubly sure, I added a fetch request before and after the deletion, and logged the total number of items in the context. This is where it gets weird.

I found that the very act of executing the fetch removed my initial bug. In other words, if I execute a fetch before and after the deletion, I can clearly see that the number of items in the context is reduced by one. However, without this fetch, the item is not deleted (or at least not immediately).

Does anyone have some insight into what is happening here?

Upvotes: 1

Views: 320

Answers (1)

Abizern
Abizern

Reputation: 150595

the deleteObject method doesn't actually remove the object - it marks it for deletion. The changes aren't actually made until the changes are committed.

Edited to add

To expand on the answer in response to the comments:

If you want to know if the context has changed so you know when to fire off a fetch request then you can register to observe the NSManagedObjectContextObjectsDidChangeNotification which is sent when an object in the context is sent a deleteObject message.

Upvotes: 1

Related Questions