does not Core Data Automatically take care with inverse relationships

2k Views Asked by At

I have 3 entities like this:

sorry that this image has a problem that the "day" relationship of "Week" entity should be to-many, there should be 2 arrows on the end of the relationship

sorry that this image has a problem that the "day" relationship of "Week" entity should be to-many, there should be 2 arrows on the end of the relationship

now here comes 2 questions.

1st. For any Day-Class (Customized subclass of NSManagedObject) objects, after I take care about its relationships like:

Week* aWeek;
Day *aDay;
[aWeek addDayObject:aDay];

then I can truely find the Day through the Week Entity's relationship "day",

but inversely, I found that the relationship "thisWeek" of the Day object "aDay" is still nil.

I've heard that after you creat your subclass of NSMangedObject, you got methods like

- (void)addXXXObject:(xxx)xxx

to help you deal with to-many relationships and would automatically take care with the inverse relationship.

but here it seems not. So do I have to deal with the inverse relationship by my self,

or if core data does provide, how can I make it automatically add the object on the inverse relationship?

2nd. Suppose there are many "Day"s with one "Week", connected by their relationship,

what I want is , everytime the user delete one of the Days, we check whether if the Week still has some Days in relationship,

if it does, just let the user delete that Day,

if not, we also delete the "Week" object.

So what Delete Rule of the to-many relationship should I use?

I'm not so clear with these rules..

Thanks!

1

There are 1 best solutions below

0
On BEST ANSWER

CoreData should actually take care of the inverse relationship as long a you defined it in both entities. See here.

I would use nullify delete rule for the day->week relationship and cascade for week->day.
When you delete the week, all days associated with it would get deleted too.
When you delete a day, it will be removed from the week's days. You cannot auto-delete the week when it has no days anymore. You can, however, observe the the week's days and delete self if self.days.count == 0.