NSPredicate with Multiple parameters NSPredicate with Multiple parameters xcode xcode

NSPredicate with Multiple parameters


Assemble an appropriate collection of individual predicates into NSCompoundPredicate

as in

NSMutableArray *parr = [NSMutableArray array];if([brand_one length]) {     [parr addObject:[NSPredicate predicateWithFormat:@"brand_id LIKE %@",myBrandId]];}if([brand_two length]) {      // etc }NSPredicate *compoundpred = [NSCompoundPredicate andPredicateWithSubpredicates:parr];

You can stack up your predicates with orPredicateWithSubpredicates: and andPredicateWithSubpredicates: and NSCompoundPredicate being a NSPredicate itself can be compounded.

See https://developer.apple.com/documentation/foundation/nscompoundpredicate


For those who are interested in Swift!

let arrPred = [NSPredicate(format: "yourAttribute LIKE %@", toCompareID), NSPredicate(format: "yourAttribute2 LIKE %@", toCompareID2)] //Add as many predicates you want in short make your querylet compoundpred:NSPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: arrPred)var arrFiltered = yourArray.filteredArrayUsingPredicate(compoundpred)


It's pretty simple to build the predicate dynamically: combine your predicate format string with desired number of conditions and build corresponding NSMutableArray with the arguments. [NSPredicate predicateWithFormat:argumentArray:] will do the rest.