您好 需要谓词方面的帮助。问题是我想要一个函数从数据库中获取取决于它接收到的多个值,但这些值并不总是存在,这是否意味着我必须创建几个不同的谓词?
下面的代码
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 等有时存在,有时不存在。
例如,对于 item_gender 应该如何处理。让我们如果没有指定性别而不是同时拥有它们。
抱歉,如果我对问题的描述令人困惑。
基于 Gobras 注释,生成了以下代码
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];
什么搜索功能应该做的逻辑解释
基于 5 个品牌 ID、商品 ID、商品类别、商品品牌、商品性别的谓词,
如果上述任何一项为空,它应该获取所有相关条目,例如,如果项目类别为空,它应该获取所有“珠宝、 watch 等”,但使用其余的谓词表达式来限制它。
我应该为品牌创建例如复合谓词,而不是为具有值“item_category like Jewellery”和“item_category like Watches”的项目类别创建另一个谓词,然后我如何将它们准确地组合在一起?
最佳答案
将适当的单个谓词集合组装到 NSCompoundPredicate
中
如
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];
你可以用
orPredicateWithSubpredicates:
来叠加你的谓词和 andPredicateWithSubpredicates:
和 NSCompoundPredicate 作为 NSPredicate 本身可以复合。看
https://developer.apple.com/documentation/foundation/nscompoundpredicate
关于xcode - 带有多个参数的 NSPredicate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6277921/