Query embedded list of objects in realm swift

Viewed 277

How to query an embedded list of objects in realm conditionally. Querying only an embedded object looks straight forward according to the documentation, but the list of embedded objects part is bothering me a lot. Also Can we use transforms like map and filter ?

For example, if I wanted to get all addresses with city as "abc" for a business "xyz" with the below models

class Address: EmbeddedObject {
    @Persisted var street: String?
    @Persisted var city: String?
    @Persisted var country: String?
    @Persisted var postalCode: String?
}

class Business: Object {
    @Persisted var name = ""
    @Persisted var addresses: List<Address> // Embed an array of objects
    convenience init(name: String, addresses: [Address]) {
        self.init()
        self.name = name
        self.addresses.append(objectsIn: addresses)
    }
}
1 Answers

You can use any high order function with Realm (map, reduce etc)

HOWEVER

in doing do you're negating the lazy-loading nature of Realm objects e.g. instead of being lazily loaded, ALL of the objects are loaded into memory which could overwhelm the device.

To answer your question; there are several ways to query for business xyz and get city abc from the addresses; here's one option

let xyzBusiness = realm.objects(Business.self).where { $0.name == "xyz" }.first!

let addressResults = xyzBusiness.addresses.where { $0.city == "abc" }

for addr in addressResults {
    print(addr)
}

Please work safely with optionals in your own code, I didn't do so in the above example.

Related