如何使用“OR”和“AND”创建复合预测

时间:2013-01-16 19:38:04

标签: iphone ios

我提取了以下3个类别,但是想要添加“AND”谓词来缩小“标记”所在的结果范围。

NSMutableArray *questionNumberArray=[[NSMutableArray alloc] init];

// Fetch questions
NSManagedObjectContext *context = self.document.managedObjectContext;
NSFetchRequest *fetchRequest =
[[NSFetchRequest alloc] initWithEntityName:@"Questions"];

//building the predicate with selected category
NSMutableArray *parr = [NSMutableArray array];

if ([cat0str length]){
    [parr addObject:[NSPredicate predicateWithFormat:@"question.category CONTAINS[c] %@",cat0str]];
}
if ([cat1str length]){
    [parr addObject:[NSPredicate predicateWithFormat:@"question.category CONTAINS[c] %@",cat1str]];
}
if ([cat2str length]){
    [parr addObject:[NSPredicate predicateWithFormat:@"question.category CONTAINS[c] %@",cat2str]];
}

NSPredicate *compoundPredicate = [NSCompoundPredicate orPredicateWithSubpredicates:parr];

[fetchRequest setPredicate:compoundPredicate];

    NSPredicate *markPredicate =[NSPredicate predicateWithFormat:@"question.mark == 1"];
}

//我想做那样的事情:

NSPredicate *finalPredicate = [compoundPredicate && markPredicate];

[fetchRequest setPredicate:finalPredicate];

1 个答案:

答案 0 :(得分:1)

这是你在找什么?

NSPredicate *finalPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:
         [NSArray arrayWithObjects:compoundPredicate, markPredicate, nil]];

或者,使用容器文字的“现代Objective-C”语法:

NSPredicate *finalPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:
                                     @[compoundPredicate, markPredicate]];