Core Data Deletion rules and many-to-many relationships

后端 未结 2 1433
感情败类
感情败类 2021-01-02 03:58

Say you have departments and employees and each department has several employees, but each employee can also be part of several departments.

So there is a many-to-ma

2条回答
  •  灰色年华
    2021-01-02 04:45

    A cascade rule will automatically delete the objects at the destination. So, if you delete a department, the employees will be deleted regardless of the number of departments they're in.

    It sounds like the behavior you want is a little more nuanced, to delete only the "orphaned" employees -- i.e. those that don't have a department. When you delete a department, a good way of finding those would be to do something like this:

    NSManagedObject *doomedDepartment = // get the department to be deleted
    
    NSSet *employees = [doomedDepartment valueForKey:@"employees"];
    NSSet *orphanedEmployees = [employees filteredSetUsingPredicate:[NSPredicate predicateWithFormat:@"departments.@count == 1"]];
    for (NSManagedObject *orphanedEmployee in orphanedEmployees) {
        [managedObjectContext deleteObject:orphanedEmployee];
    }    
    
    [managedObjectContext deleteObject:doomedDepartment];
    

提交回复
热议问题