NSComparisonPredicate用于空对多关系

时间:2013-09-15 02:33:03

标签: ios objective-c core-data nspredicate

我在Core Data中的两个实体(EntityA和EntityB)之间存在多对多关系,我正在尝试通过删除不再与任何实例关系的EntityB实例来定期清理数据库。 EntityA。我正在使用Mogenerator来创建.m和.h文件,这允许我像我一样引用属性/关系名称。

NSPredicate *noRelationPredicate = [NSComparisonPredicate predicateWithLeftExpression:[NSExpression expressionWithFormat:@"%K", EntityBRelationships.relationshipNameForEntityA] rightExpression:[NSExpression expressionWithFormat:@"nil"] modifier:NSDirectPredicateModifier type:NSEqualToPredicateOperatorType options:0];

但是,当我执行fetch时遇到以下错误:'NSInvalidArgumentException',原因:'to-many key not here here'

我更喜欢使用类方法NSComparisonPredicate predicateWithLeftExpression:rightExpression:modifier:type:options:创建谓词,因为我试图避免在谓词创建中使用字符串文字。

2 个答案:

答案 0 :(得分:1)

您可以向实体B添加一个类别,以检查是否可以删除它。

-(void)willSave {
    if (!self.aRelations.count && !self.isDeleted) {
        [self.managedObjectContext deleteObject:self];
    }
}

(通过在单独的文件中使用类别,如果要重新生成托管对象子类,则不会覆盖此代码。)

答案 1 :(得分:0)

在定义关系时,可以指定CoreData应对“孤立”实例执行的操作。请参阅此处的“关系删除规则”:https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CoreData/Articles/cdRelationships.html#//apple_ref/doc/uid/TP40001857-SW1

特别是,您可以使用“Cascade”来为您处理删除。来自文档:

  

级联

     

删除关系目的地的对象。对于   例如,如果删除某个部门,则解雇其中的所有员工   部门在同一时间。