Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
637 views
in Technique[技术] by (71.8m points)

objective c - Core Data delete rule -- to-many relationship, delete when empty

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 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

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:

  • 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?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...