Search code examples
swiftrealmnspredicate

NS Predicate search for "do not have any"


I have a simple data model:

class Dog: Object {
    dynamic var Name : String = ""
    let Colour = List<ColourItem>()
}

class ColourItem: Object {
    dynamic var colourName = ""
}

And I can do NSPredicate searches for all Dogs, or Dogs with a specific colour assigned to them:

let importPredicate = NSPredicate(format: "%@ IN Colour.colourName", colourVar)
let results = realm.objects(Dog).filter(importPredicate)

But I am stuck on how to search for just Dogs without any colour assigned to them. (i.e.: I want to filter for dogs whose Colour property is empty).

Any ideas/hints?


Solution

  • You can query for dogs with an empty Colour list like so:

    let results = realm.objects(Dog.self).filter("Colour.@count == 0")