xcode - 带有多个参数的 NSPredicate

标签 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]];

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/

    相关文章:

    ios - NSPredicate 嵌套子查询编译失败(核心数据)

    ios - 迭代传递给 View 的核心数据

    ios - 发现扩展时遇到 Swift 4 错误 - 照片无法在 UI 上加载

    iphone - 核心数据与同一实体的多个关系

    ios - 如何从 CoreData 检索经度和纬度

    objective-c - 使用filteredArrayUsingPredicate方法通过属性从数组中过滤对象

    ios - MPMoviePlayerController:在控制元素后面添加 subview

    ios - 由于信号 : Killed: 9,Xcode 8 (Swift 3) 命令失败

    uitableview - 在 Swift 中的自定义单元格中存储/检索核心数据

    ios - NSArray 和 NSPredicate 使用 NOT IN