Search code examples
iosswiftnspredicate

Create NSPredicate with ANY and two conditions for it


I simply have two entities: Product and Item. Product may have many items: Set<Item>. Item has two properties: isActive and identifier.

Now I need to fetch all Products which have at least one Item with the following conditions met the same time:

  • identifier IN %@ //["1", "2"]

  • isActive = true

      let format = "ANY (items.identifier IN %@ AND items.isActive = true)"
      let predicate = NSPredicate(format: format, ["1", "2"])
    

But I got exception: Unable to parse the format ...

Why?


Solution

  • You can try this -

    let format = "SUBQUERY(items, $item, $item.identifier IN %@ AND $item.isActive = true).@count > 0"
    let predicate = NSPredicate(format: format, ["1", "2"])
    

    Source : NSPredicate Cheatsheet