Core Data删除规则对多关系,删除时为空 [英] Core Data delete rule -- to-many relationship, delete when empty
问题描述
我对于Core Data中关系的删除规则如何工作有点模糊,至少超出了文档中描述的简单情况。
大多数这些情况,以及我在这里看到的大多数答案,使用一个模型,其中对象在一对多关系的左侧拥有右侧的对象:例如
有
PhoneNumber
,如果删除此人,则删除其所有关联的号码。在这种情况下,解决方案是明确的:如果您设置如下关系,Core Data将处理一切:
人 - (级联) - >> PhoneNumber
PhoneNumber - (nullify) - > Person
我感兴趣的是相反的:一对多的关系,反转。例如,我可以扩展CoreDataBooks示例代码以添加作者
实体,用于在一个地方收集有关唯一作者的所有信息。 A Book
有一个作者,但作者有很多书...但我们不关心我们不列出书籍的作者。因此,删除作者
的 books
关系不是空的,并且删除最后一个 Book
引用特定作者
应删除作者
。
我可以想象几种方法来手动执行此操作...我不确定是什么:
- Core Data有一种自动执行此操作的方法,如关系删除规则中所述?
- 有一个规范 您可以覆写
prepareForDeletion $ c $ c>在您的
Book
类,并检查作者是否有任何其他书籍。- (void)prepareForDeletion {
作者* author = self.author;
if(author.books.count == 1){//只有书本身
[self.managedObjectContext deleteObject:author];
}
}
编辑:为了防止作者被删除可以覆盖
validateForDelete
或更好:不要调用deleteObject与作者首先有书I'm a little fuzzy on how the delete rules for relationships in Core Data work, at least beyond the simple cases described in the documentation.
Most of those cases, and most of the answers I've seen for questions here, use a model where the object on left side of a one-to-many relationship "owns" the objects on the right side: e.g. a
Person
hasPhoneNumber
s, and if you delete the person you delete all their associated numbers. In that kind of case, the solution is clear: Core Data will handle everything for you if you set the relationships like so:Person --(cascade)-->> PhoneNumber PhoneNumber --(nullify)--> Person
What I'm interested in is the opposite: A to-many relationship where the "ownership" is reversed. For example, I might extend the CoreDataBooks sample code to add an
Author
entity for collecting all info about a unique author in one place. ABook
has one author, but an author has many books... but we don't care about authors for whom we don't list books. Thus, deleting anAuthor
whosebooks
relationship is non-empty should not be allowed, and deleting the lastBook
referencing a particularAuthor
should delete thatAuthor
.I can imagine a couple of ways to do this manually... what I'm not sure of is:
- does Core Data have a way to do at least some of this automagically, as with relationship delete rules?
- is there a "canonical", preferred way to handle this kind of situation?
解决方案You could override
prepareForDeletion
in yourBook
class and check if the author has any other books. If not you could delete the author.- (void)prepareForDeletion { Author *author = self.author; if (author.books.count == 1) { // only the book itself [self.managedObjectContext deleteObject:author]; } }
Edit: To prevent deletion of an author with books you could override
validateForDelete
or even better: don't call deleteObject with an author with books in the first place这篇关于Core Data删除规则对多关系,删除时为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!