iOS - CoreData -> deleting an object which has no relations anymore

I think my title is not explaining the situation correctly so I am going to explain a bit more.

I have topics, which is one to many. These are related to sessions. Sessions are related to Subjects one to many. Subjects are related to speakers many to many.

So here is the problem. If I delete a speaker, if the subject which is spoken by this speaker has no more speakers, should be removed too. And the session should be removed too, if no more subjects exist related to it. And it goes on.

It's a bit complicated and need too many lines to write. Is there any pre-defined option to do that?

Thanks for help.

Upvotes: 0

Views: 41

Answers (2)

Mundi
Mundi

Reputation: 80265

You can override the Core Data generated methods for removing a to-many relationship. Just make sure you call those methods. I recommend implementing these in categories of the managed object subclasses.

For example on the bottom level, for Speakers, you just use the remove method of the Subject entity:

-(void)removeSpeakersObject:(Speaker *)value {
   [super removeSpeakersObject:value];
   if (!self.speakers.count) {
        [self.session removeSubjectsObject:self];
   }
}

You do the equivalent in the Session and Topic classes.

Upvotes: 1

Aditya Sinha
Aditya Sinha

Reputation: 103

Here's a solution:

Your hierarchy is like this:

Topics -> Sessions -> Subjects -> Speakers.

Then to quote from Apple docs:

Cascade : Delete the objects at the destination of the relationship. For example, if you delete a department, fire all the employees in that department at the same time.

Thus, you should set cascade property for Sessions, Subjects and Speakers.

Cascade

Hope this helps.

Upvotes: 1

Related Questions