0

Given a Core data app. I'd like to prevent a deletion if a relationship is not empty.

The best method seems to be with validateForDelete. Yet, when quering the size of the relationship it returns 0.

The following sets all return a non-nil object but a count of 0.

 - (BOOL)validateForDelete:(NSError **)error {
     NSSet *emp0 = [self employees];
     NSSet *emp1 = [self valueForKey:@"employees"];
     NSMutableSet *emp2 = [self mutableSetValueForKey:@"employees"];
     ...
     if ([emp0 count] <= 0) return YES:
     else return NO;
 }

The set is definately not empty. Perhaps the NSArrayControllers are not properly configured..!

Gabe Rainbow
  • 3,658
  • 4
  • 32
  • 42
  • Urgh. Now it returns the proper count -- if the relationship is set to 'Deny.' But set to 'Cascade' the count is 0. Now, the second problem: the Entity is deleted . Or at least, removed from the Controller and, or marked for delete. – Gabe Rainbow Apr 25 '13 at 23:11

1 Answers1

0

After a bunch of digging around, neither validateForDelete or prepareDelete are intended to preventDelete (on self).

Essentially what is desired is to check the size or count of the relationship, that of a NSSet.

http://www.cocoabuilder.com/archive/cocoa/232242-nsmanagedobject-validatefordelete-problem.html

Using Cascade Delete Rule and validateForDelete on a One-to-Many Relationship in iPhone Core Data (Of limited use given that NSCascade will delete the owned objects, as desired in this case)

Here is my solution on the ArrayController.

@implementation NSArrayController (PreventDeleteController)

- (BOOL)canRemove {

    NSArray *selected = [self selectedObjects];
    NSEnumerator *objEnum = [selected objectEnumerator];

    while ((NSManagedObject *obj = [objEnum nextObject]))
    {
        NSDictionary *relationships = [[obj entity] relationshipsByName];   

        for(NSString *key in [relationships allKeys]) {
            id relationship = [relationships objectForKey: key];

            if([relationship deleteRule] == NSDenyDeleteRule ) {

                if ([[obj mutableSetValueForKey:key] count]) { 
                          //CHECK THE COUNT OF THE RELATIONSHIP HERE
                    return NO;
                }
            }
        }
    }

    return [super canRemove];
}
Community
  • 1
  • 1
Gabe Rainbow
  • 3,658
  • 4
  • 32
  • 42