CoreData delete object

*爱你&永不变心* 提交于 2019-12-21 12:17:29

问题


Why doesn't the prepareForDeletion: method get called?

I'm deleting an object using its ancestor relationship:

[folder removeDocumentObject: doc];

The "doc" object gets deleted like expected, but its prepareForDeletion method never gets called... =\


回答1:


Because it's not being deleted :)

If [folder documentObject] returns nil that just means that there is no relationship between the two objects. It doesn't mean that the object is deleted from core data.

Try this :

[[doc managedObjectContext] deleteObject:doc];

EDIT

Using this code I have tested your problem :

I have made a new project with a Document and Folder object in Core Data - it's set to folder <<--> document with cascasde set on the folder relationship.

// 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's 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's 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 string for the title.

The second NSLog statements crash because the document doesn't exist in the store any more.

This tells me that just removing a relationship isn't enough to remove the Document from the store - you have to explicitly delete it. However, you say that you think it's deleted. Can you post the query that you are running to see if it's still in the store or not?



来源:https://stackoverflow.com/questions/4638692/coredata-delete-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!