Search code examples
objective-cnspredicatensfetchedresultscontrollerpredicate

Combining + andPredicateWithSubpredicates: and + orPredicateWithSubpredicates: in one predicate


I want to set a compound predicate with next subpredicates:

  • id (AND type)
  • firstname (OR type)
  • lastname (OR type)
  • middlename (OR type)

I am reading NSCompoundPredicate documentation but don't understand clear enough - is it possible at all to use both + andPredicateWithSubpredicates: and + orPredicateWithSubpredicates: to combine them as one predicate in one fetch request?


Solution

  • Solved this way:

    objc:

    NSPredicate *orPredicate = [NSCompoundPredicate orPredicateWithSubpredicates:@[firstPredicate, secondPredicate]];
    NSPredicate *andPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:@[thirdPredicate, fourthPredicate]];
    NSPredicate *finalPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:@[orPredicate, andPredicate]];
    [fetchRequest setPredicate:finalPredicate];
    

    Swift:

    let orPredicate = NSCompoundPredicate(orPredicateWithSubpredicates: [firstPredicate, secondPredicate])
    let andPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [thirdPredicate, fourthPredicate])
    fetchRequest.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [orPredicate, andPredicate])