NSPredicate具有多个参数

Rou*_*mov 24 xcode core-data nspredicate

你好需要谓词的帮助.问题是我希望有一个从数据库获取的函数取决于它接收的多个值,但这些值并不总是存在,这是否意味着我必须创建几个不同的谓词?

代码如下

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]];
Run Code Online (Sandbox Code Playgroud)

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];
Run Code Online (Sandbox Code Playgroud)

关于搜索功能应该是什么的逻辑解释

  1. fetchrequest
  2. 获取请求的谓词

基于5个品牌ID,商品ID,商品类别,商品品牌,商品性别的谓词,如果以上任何一个为空,则应获取所有相关条目,例如,如果商品类别为空,则应获取所有"珠宝,手表等"但用其余的谓词表达式限制它.

我应该为品牌创建例如复合谓词,而不是为项目类别创建另一个值为"item_category like Jewellery"和"item_category like Watches",之后如何将它们完全组合在一起?

War*_*ton 62

将适当的单个谓词集合组合成 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];
Run Code Online (Sandbox Code Playgroud)

你可以用orPredicateWithSubpredicates:和堆叠你的谓词andPredicateWithSubpredicates:和NSCompoundPredicate是一个NSPredicate本身可以复合.

请参阅 https://developer.apple.com/documentation/foundation/nscompoundpredicate