Filter Embedded Object List

We have a use case where we need to filter on a List of Embedded objects before they are stored in Realm. Doing this throws an error

This method may only be called on RLMArray instances retrieved from an RLMRealm

Given a PersonClass object and an EmbeddedAddress embedded object

class PersonClass: Object {
   @objc dynamic var name = ""
   let addressList = List<EmbeddedAddress>()

class EmbeddedAddress: EmbeddedObject {
   @objc dynamic var name = ""

here’s the code that crashes

let person = PersonClass() = "Ted"

let a = EmbeddedAddress() = "a"

let b = EmbeddedAddress() = "b"

let c = EmbeddedAddress() = "c"

person.addressList.append(objectsIn: [a, b, c])

for addr in person.addressList {
   print( // prints a, b, and c

let result = person.addressList.filter("name == 'b'") //CRASH

The use case is a user creates a person and as addresses are being added, we want to ensure they are unique before saving so we need to filter to see if the entered address was already entered.

Hi @Jay

This is the intended behaviour. If you intend to use a collection of Realm Results then you must add the object to the Realm.

Thank you @Lee_Maguire

Does that mean Realm provides no filtering for a List of Embedded objects - that will need to be done using Swift only?

We provide filtering as long as your person object is managed. Otherwise you can use the Swift Foundation filter function.

Thanks @Lee_Maguire

Perhaps I am looking at this incorrectly but the following code to get the first match for Addr 10 won’t compile

if let foundAddr = person.addressList.filter { $ == "Addr 10" }.first {

Anonymous closure argument not contained in a closure

However, if I do this with a non-embedded object, it works fine.


Any thoughts or suggestions on the above?