Mateus Mateus - 1 year ago 153
Objective-C Question

Core Data fault after deleting managed object

Basically, I'm trying to access some properties of a NSManagedObject after deleting it from the NSManagedObjectContext and saving the context. The problem is that, after saving the context, Core Data marks the object data as fault and, apparently, is unable to recover it.

I've created a sample project in order to replicate the issue, you can download it here. To illustrate, the following snippet:

City *city = [self.cities objectAtIndex:indexPath.row];
[self.managedObjectContext deleteObject:city];
if (![self.managedObjectContext save:&error]) {
[self.managedObjectContext rollback];
NSLog(@"Error: %@", error);
NSLog(@"%@", city);
// All properties of "city" are zeroed.
// Saved. Update data sources and animate changes...


<City: 0x7fe1cbd3cba0> (entity: City; id: 0xd000000000040004 <x-coredata://C1E3D3D8-188D-41DE-B701-08AF6D3E8860/City/p1> ; data: {
country = "0xd000000000080002 <x-coredata://C1E3D3D8-188D-41DE-B701-08AF6D3E8860/Country/p2>";
name = Rosario;

<City: 0x7fe1cbd3cba0> (entity: City; id: 0xd000000000040004 <x-coredata://C1E3D3D8-188D-41DE-B701-08AF6D3E8860/City/p1> ; data: <fault>)

The reason I'd like to access the managed object, after deleting it, is to update a NSMutableArray which acts as data source for a table view and update another data source in a previous controller in the navigation controller stack (This is not implemented in the sample project).

Wrapping up, my questions are:

After deleting a NSManagedObject from its NSManagedObjectContext and saving the context, it is no longer guaranteed that the data in the managed object will be accessible? Even if a reference to that managed object is kept?

Based on what i've researched, Core Data is getting rid of the entity data to save memory once the context is saved. Is this assumption correct? Are there other factors that might be causing this data faulting?


Answer Source

An NSManagedObject is always dynamically rendered. Hence, if it is deleted, Core Data faults out the data. It doesn't exist anymore. Your real question is how to remove an object from your various arrays? First, you should remove it before you delete the object using whichever search techniques you wish. This is the easiest and most robust path. Second, the object pointer itself is still valid and can be used with a -removeObject: call. Allow me to emphasize though, this is a fragile solution. I'm strongly encouraging you to remove the object before deleting it.

In answer to your second question,

Are there other factors that might be causing this data faulting?

No. Deleting the object is causing the faulting. If the data has heretofore been available, that is due to it being an implementation characteristic. Writing to the implementation instead of the spec, especially with database technologies, is brought with all sorts of life cycle problems. Quoting the wise Doctor, "Don't do that."