Search code examples
swiftlistrealm

Filter querying multiple objects from Realm using List of Primary Keys


I'm trying to query multiple objects from Realm using a List of Primary Key Strings. I know I can do this using a for..in loop but I'd rather use a filter if possible.

primaryKeyArray contains a number of Strings

class Item : Object {
    @objc dynamic var itemKey = NSUUID().uuidString
}

var primaryKeyArray : List<String>?

//Assume Realm DB already contains multiple Item Objects 
//primaryKeyArray contains "key1", "key2", "key3", etc..

let predicate = NSPredicate(format: "itemKey == %@", primaryKeyArray)

let items = realm.objects(Item.self).filter(predicate)

I know the problem is with my predicate format. Not sure whether to use some form of CONTAINS or what? Any help with the predicate syntax would be greatly appreciated!


Solution

  • I think you are asking how to query Realm for items that have keys that match a set of keys in an array.

    So given a DogClass Realm Object

    class DogClass: Object {
        @objc dynamic var dog_id = NSUUID().uuidString
        @objc dynamic var dog_name = ""
    
        override static func primaryKey() -> String? {
            return "dog_id"
        }
    }
    

    and suppose we know we want to retrieve three dogs that match some given primary keys

    let keysToMatch = ["302AC133-3980-41F3-95E8-D3E7F639B769", "54ECC485-4910-44E5-98B9-0712BB99783E", "71FE403B-30CD-4E6C-B88A-D6FDBB08C509"]
    let dogResults = realm.objects(DogClass.self).filter("dog_id IN %@", keysToMatch)
    for dog in dogResults {
        print(dog.dog_id, dog.dog_name)
    }
    

    Note the use of IN in the filter, which will match any dogs with id's in the given array.

    You can also pass in a Realm List Object instead of a Swift array and get the same result.

    let listOfKeysToMatch = List<String>()
    listOfKeysToMatch.append("302AC133-3980-41F3-95E8-D3E7F639B769")
    listOfKeysToMatch.append("54ECC485-4910-44E5-98B9-0712BB99783E")
    listOfKeysToMatch.append("71FE403B-30CD-4E6C-B88A-D6FDBB08C509")
    let dogResults2 = realm.objects(DogClass.self).filter("dog_id in %@", listOfKeysToMatch)
    for dog in dogResults2 {
        print(dog.dog_id, dog.dog_name)
    }