swiftrealm

Realm Swift - Find by IDs


I need to query Realm objects using a list of ids, id being the object's primary key. I have tried the following:

// Query a list of Dogs by their _ids
let doggoIds = ["1", "2", "3", "1", "2"]
realm.objects(Dog.self).filter("_id IN %@", doggoIds)
// Result: [Dog1, Dog2, Dog3]

The list of ids contains duplicates, but as you can see the result is a list of unique Dog objects.

I'm wondering if anyone can think of a different way to write this query so that we get a nice Results<Dog> collection from that list of ids that includes duplicates. Thanks!


Solution

  • Realm.objects().filter returns a list of "live", managed objects. It will not return duplicates because there is only one object matching the primary key. In order to accomplish what you want, you'll need to create an 'unmanaged' duplicate of each object and make your own array of those unmanaged objects map each returned instance into your own array.

    A la:

    let doggoIds = [1, 2, 3, 1, 2]
        for managedMuttId in doggoIds {
            if let managedMutt = realm.object(ofType: Dog.self, forPrimaryKey: managedMuttId) {
                // unmanaged.append(Dog(value: managedMutt))
                duplicateList.append(managedMutt)
            }
        }