Core Data Deletion rules and many-to-many relationships

后端 未结 2 1434
感情败类
感情败类 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:38

    Thanks, alex. I will probably do that. In the meantime I had found a different way of doing this:

    1.) register for notifications on changes:

        [[NSNotificationCenter defaultCenter] addObserver:self 
                selector:@selector(managedObjectContextDidChange:) 
                name:NSManagedObjectContextObjectsDidChangeNotification 
                object:managedObjectContext];
    

    2.) when changes occur and an employee gets updated. I check if that object has 0 relations to departments and delete it:

    - (void)managedObjectContextDidChange:(NSNotification *)notification {
        NSSet *updatedObjects = [[notification userInfo] objectForKey:NSUpdatedObjectsKey];
    
    for(NSManagedObject *obj in updatedObjects){        
        // walk through updated objects -> check for employees
        // check if they still contain departments and if not delete them
        if([obj.entity.name isEqualToString:@"Employee"]){
            NSLog(@"Employee changed!");
            if([[(Employee*)obj Departments] count]==0){
                NSLog(@"No more relations -> Delete Employee");
                [managedObjectContext deleteObject:obj];
            }
        }
    }}
    

    That works well too, but might get more complicated if you have several different entities for which to observe this kind of behavior.

提交回复
热议问题