'Realm Swift: Filtering objects by nested List property using IN predicate
I have the following Realm Object structure:
class ParentObject: Object {
let nestedObjects = List<NestedObject>
}
class NestedObject: Object {
@objc dynamic var id: Int = 0
}
Is it possible to filter ParentObjects to return only those that contain NestedObjects whose id matches one of those contained in an array?
I tried doing it this way:
let ids = [1, 2, 3]
let filtered = realm
.objects(ParentObject.self)
.filter("nestedObjects.id IN %@", ids)
But I'm getting this error: Terminating app due to uncaught exception 'Invalid predicate', reason: 'Key paths that include an array property must use aggregate operations'.
Maybe I should try doing it with multiple ORs instead of IN?
Solution 1:[1]
You want a predicate of ANY nestedObjects.id IN %@. The ANY/ALL/NONE modifier is important as it determines how many of the objects in the collection must match for the predicate to evaluate to true.
Solution 2:[2]
new realm safe query syntax (10.19 I think) : example looking for all parents with a nested object with id = myID and with a type = myType
let filtered = realm
.objects(ParentObject.self)
.where ({ parent in
parent.nestedObjects.id == myId &&
parent.nestedObjects.type == myType
})
with old predicate syntax :
let filtered = realm
.objects(ParentObject.self)
.filter("ANY nestedObjects.id IN %@", [myId])
.filter("ANY nestedObjects.type IN %@)", [myType])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | bdash |
| Solution 2 | Vassily |
