核心数据删除规则——一对多关系,空时删除 [英] Core Data delete rule -- to-many relationship, delete when empty

查看:41
本文介绍了核心数据删除规则——一对多关系,空时删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Core Data 中关系的删除规则的工作方式有点模糊,至少超出了文档中描述的简单情况.

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.

大多数情况,以及我在这里看到的大多数问题的答案,都使用一个模型,其中一对多关系左侧的对象拥有"右侧的对象:例如PersonPhoneNumbers,如果你删除这个人,你就会删除他们所有的关联号码.在这种情况下,解决方案很明确:如果您像这样设置关系,Core Data 将为您处理一切:

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 has PhoneNumbers, 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

我感兴趣的是相反的:所有权"颠倒的多对多关系.例如,我可能会扩展 CoreDataBooks 示例代码以添加一个 Author 实体,用于在一个地方收集有关唯一作者的所有信息.Book 有一个作者,但一个作者有很多本书……但我们不关心我们没有列出书籍的作者.因此,不应允许删除 books 关系为非空的 Author,并删除引用特定 Author 的最后一个 Book 应该删除那个 Author.

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. A Book 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 an Author whose books relationship is non-empty should not be allowed, and deleting the last Book referencing a particular Author should delete that Author.

我可以想象有几种方法可以手动执行此操作...我不确定的是:

I can imagine a couple of ways to do this manually... what I'm not sure of is:

  • Core Data 有没有办法像关系删除规则那样至少自动执行其中的某些操作?
  • 是否有一种规范的"、首选的方式来处理这种情况?

推荐答案

你可以在你的 Book 类中覆盖 prepareForDeletion 并检查作者是否有任何其他书籍.如果没有你可以删除作者.

You could override prepareForDeletion in your Book 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];
    }
}

为了防止删除有书籍的作者,您可以覆盖 validateForDelete 甚至更好:不要首先使用有书籍的作者调用 deleteObject

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

这篇关于核心数据删除规则——一对多关系,空时删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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