I have three objects nested via lists like this:
class Canteen: Object {
dynamic var name: String?
let lines = List<Line>()
}
class Line: Object {
dynamic var name: String?
let meals = List<Meal>()
}
class Meal: Object {
dynamic var name: String?
dynamic var vegan: Bool = false
}
Getting all canteens with all the lines and meals is no problem. What im doing right now is this:
let predicate = NSPredicate(format: "name == %@", selectedCanteenType.rawValue)
canteens = realm.objects(Canteen).filter(predicate)
But now i only need the meals which are vegan. So im looking to get the selected canteen with all the lines, but only with meals which are vegan. Is this possible in realm, to filter lists in retrieved objects?
Realm allows it to use functions as parameter for the filtering. So this is my solution which im currently using.
The two filter functions:
The functions filter all meals which are not vegetarian or vegan when the user has selected
showVegetarianOnly = true
. Also it filters all lines which than have no meal left (nothing is vegetarian or vegan).Most important functions of the TableView:
Try this:
Realm doesn't have any sort of concept of a deep-filtered view, so you can't have a
Results<Canteen>
which restricts theList
s contained in related objects to vegan meals.There are several similar things which you can do. You could add inverse relationship properties, and then query
Meal
objects instead:(Or rather, you will be able to once Realm 0.102.1 is out; currently this crashes).
If you just need to iterate over the meals but need to do so from the Canteen down, you could do:
This unfortunately has some duplication due to needing to repeat the filter for each level of the references.