为什么不调用 prepareForDeletion: 方法?
我正在使用其祖先关系删除一个对象:
[folder removeDocumentObject: doc];
“doc”对象像预期的那样被删除,但它的 prepareForDeletion 方法从未被调用...=\
最佳答案
因为它没有被删除:)
如果 [folder documentObject]
返回 nil,则意味着两个对象之间没有任何关系。这并不意味着该对象已从核心数据中删除。
试试这个:
[[doc managedObjectContext] deleteObject:doc];
编辑
使用这段代码我已经测试了你的问题:
我在 Core Data 中创建了一个包含文档和文件夹对象的新项目 - 它设置为文件夹 <<--> 文档,在文件夹关系上设置了级联。
// 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]);
前两个 NSLog 语句工作正常 - 我得到了文档的描述和标题的字符串。
第二个 NSLog 语句崩溃,因为存储中不再存在该文档。
这告诉我,仅删除关系不足以从商店中删除文档 - 您必须明确删除它。但是,你说你认为它被删除了。您能否发布您正在运行的查询以查看它是否仍在商店中?
关于iphone - CoreData删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4638692/