CoreData Removal Object

Why is the prepareForDeletion method not called :?

I delete the object using its ancestor relation:

[folder removeDocumentObject: doc]; 

The doc object is deleted as expected, but its prepareForDeletion method is never called ... = \

+7
source share
1 answer

Because it is not deleted :)

If [folder documentObject] returns nil, it means that there is no connection between the two objects. This does not mean that the object is removed from the master data.

Try the following:

 [[doc managedObjectContext] deleteObject:doc]; 

EDIT

Using this code, I tested your problem:

I created a new project with a Document object and a Folder in Core Data - it installed a document in the ↔ folder with cascasde installed in relation to the folder.

 // Create a document and folder and save them Folder *fol = [NSEntityDescription insertNewObjectForEntityForName:@"Folder" inManagedObjectContext:[self managedObjectContext]]; Document *doc = [NSEntityDescription insertNewObjectForEntityForName:@"Document" inManagedObjectContext:[self managedObjectContext]]; [doc setFolder:fol]; [[self managedObjectContext] save:nil]; // Get the document object id for later NSManagedObjectID *documentId = [doc objectID]; // Delete the relationship [fol removeDocumentsObject:doc]; [[self managedObjectContext] save:nil]; // Try to reload the document to see if it still there Document *doc2 = (Document *)[[self managedObjectContext] objectWithID:documentId]; // Get a property from the document - this will fault if the document has been deleted. Otherwise it // will work. NSLog(@"%@", doc2); NSLog(@"%@", [doc2 title]); // Now delete specifically and try again [[self managedObjectContext] deleteObject:doc]; [[self managedObjectContext] save:nil]; // Should get a fault here doc2 = (Document *)[[self managedObjectContext] objectWithID:documentId]; NSLog(@"%@", doc2); NSLog(@"%@", [doc2 title]); 

The first two NSLog statements work correctly - I get a description of the document and a line for the title.

Second NSLog statements crash because the document no longer exists in the repository.

This tells me that simply deleting the relationship is not enough to remove the Document from the store — you must explicitly delete it. However, you say you think it has been deleted. Can you post the query you use to find out if everything is in the store or not?

+16
source

All Articles