CoreData删除对象 [英] CoreData delete object

查看:74
本文介绍了CoreData删除对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不调用prepareForDeletion:方法?

Why doesn't the prepareForDeletion: method get called?

我使用它的祖先关系删除对象:

I'm deleting an object using its ancestor relationship:

[folder removeDocumentObject: doc];

doc对象按预期被删除,但其prepareForDeletion方法不会被调用... = \

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

推荐答案

因为它没有被删除:)

[folder documentObject] 返回nil,这意味着两个对象之间没有关系。

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.

请尝试以下操作:

[[doc managedObjectContext] deleteObject:doc];






EDIT


EDIT

使用这个代码我测试了你的问题:

Using this code I have tested your problem :

我在Core Data中创建了一个文档和文件夹对象的新项目 -

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]);

前两个NSLog语句可以正常工作 - 我得到文档的描述和标题的字符串。

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

第二个NSLog语句崩溃,因为文档在商店中不再存在。

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?

这篇关于CoreData删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆