nsmanagedobject关系0

时间:2013-04-25 22:54:51

标签: core-data nsmutablearray nsmanagedobject

鉴于核心数据应用。如果关系不为空,我想阻止删除。

最好的方法似乎是validateForDelete。然而,当查询关系的大小时,它返回0.

以下集合都返回非零对象,但计数为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;
 }

该集绝对不是空的。也许NSArrayControllers没有正确配置..!

1 个答案:

答案 0 :(得分:0)

经过一堆挖掘后,validateForDelete或prepareDelete都无法阻止删除(自我)。

基本上所需要的是检查关系的大小或数量,即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 (仅限于使用NSCascade将删除拥有的对象,在这种情况下需要)

这是我在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];
}