Hello Need help with predicate. The problem is that I want to have one function which will fetch from database depends on the multiple values it receives, but the values don't always exist, does it mean I have to create several different predicates?
Code below
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"brand_id LIKE %@ AND brand_id LIKE %@ AND brand_id LIKE %@ AND brand_id LIKE %@ AND brand_id LIKE %@ AND item_category LIKE %@ AND item_make LIKE %@ AND item_gender LIKE %@ || item_price>%@ || item_price<%@",
brand_one, brand_two, brand_three, brand_four, brand_five, categoryString, makeString, genderString,[NSNumber numberWithInt:price_bottom],[NSNumber numberWithInt:price_top]];
brand_one, brand_two and etc sometimes exist and sometimes don't.
And how should it for item_gender for example. Let's if there is no gender specified than to have both of them.
Sorry if my description of the problem confusing.
Base on Gobras comments the following code was produces
NSArray *brands = [NSArray arrayWithObjects:brand_one, brand_two, brand_three, brand_four, brand_five, nil];
NSPredicate *predicate_brands = [NSPredicate predicateWithFormat:@"brand_id like %@" argumentArray:brands];
Logical explanation of what what search function should
predicate based on 5 brand ids, item id, item category, item make, item gender, if any of above is empty it should fetch all related entries for example if item category is empty it should fetch all "Jewellery, Watches and etc" but limit it with the rest of the predicate expressions.
Should I create for example compound predicates for brands and than create another one for item category with values "item_category like Jewellery" and "item_category like Watches" and after that how do I exactly bring them together?
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