关系列表中的iOS Realm筛选器对象 [英] iOS Realm Filter objects in a list of a relationship

查看:141
本文介绍了关系列表中的iOS Realm筛选器对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个通过这样的列表嵌套的对象:

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没有深度过滤视图的任何概念,因此您不能使用Results<Canteen>来限制List包含在素食食品的相关对象中.

Realm doesn't have any sort of concept of a deep-filtered view, so you can't have a Results<Canteen> which restricts the Lists contained in related objects to vegan meals.

您可以执行几项类似的操作.您可以添加逆关系属性,然后查询Meal对象:

There are several similar things which you can do. You could add inverse relationship properties, and then query Meal objects instead:

class Canteen: Object {
    dynamic var name: String?
    let lines = List<Line>()
}

class Line: Object {
    dynamic var name: String?
    let meals = List<Meal>()
    let canteens = LinkingObjects(fromType: Canteen.self, property: "lines")
}

class Meal: Object {
    dynamic var name: String?
    dynamic var vegan: Bool = false
    let lines = LinkingObjects(fromType: Line.self, property: "meals")
}

let meals = realm.objects(Meal).filter("vegan = true AND ANY lines.canteens.name = %@", selectedCanteenType.rawValue)

(或者说,您将能够在Realm 0.102.1退出之后;当前会崩溃).

(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:

let canteens = realm.objects(Canteen).filter("name = %@ AND ANY lines.meals.vegan = true", selectedCanteenType.rawValue)
for canteen in canteens {
    for line in canteen.lines.filter("ANY meals.vegan = true") {
        for meal in line.meals.filter("vegan = true") {
            // do something with your vegan meal
        }
    }
}

不幸的是,由于需要为每个级别的引用重复过滤器,因此出现了一些重复.

This unfortunately has some duplication due to needing to repeat the filter for each level of the references.

这篇关于关系列表中的iOS Realm筛选器对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆