如何按列表过滤Realm对象

时间:2018-04-19 16:03:58

标签: ios swift filter realm

我有一个DeviceContactModel和一个DeviceContactPhoneModel,它继承自Object(Realm)。 DeviceContactModel有一个List <DeviceContactPhoneModel>。我想通过其中一个DeviceContactModel属性过滤DeviceContactPhoneModel。我制作了测试代码,但它调用了应用程序崩溃。请告诉我它是如何实施的?感谢。

    class DeviceContactModel: Object, Mappable {

        @objc dynamic var id = ""
        @objc dynamic var givenName = ""
        @objc dynamic var familyName = ""
        @objc dynamic var updateTimestamp = 0.0

        var isNew = false

        let phones = List<DeviceContactPhoneModel>()

    }

final class DeviceContactPhoneModel: Object, Mappable {

    @objc dynamic var id = ""
    @objc dynamic var contactID = ""
    @objc dynamic var updateTimestamp = 0.0
    @objc dynamic var countryCode: Int64 = 0
    @objc dynamic var nationalNumber: Int64 = 0
    @objc dynamic var fullNumber: Int64 = 0

}

测试功能

private func getDeviceContacts(_ phoneNumbers: [Int64]) -> [DeviceContactModel] {
        do {
            let realm = try Realm()
            let deviceContacts = Array(realm.objects(DeviceContactModel.self).filter("phones.fullNumber IN %@", phoneNumbers))
            return deviceContacts
        } catch {
            debugPrint(error.localizedDescription)
            return []
        }
    }

崩溃日志 谓词无效&#39;,原因:&#39;包含数组属性的关键路径必须使用汇总操作

2 个答案:

答案 0 :(得分:1)

尝试此解决方案

如果您使用多对多关系,则使用ANY运算符

请仔细阅读以便您了解要使用的内容,因为还有其他操作员ALL,ANY,NONE Predicate Programming Guide

 private func getDeviceContacts(_ phoneNumbers: [Int64]) -> [DeviceContactModel] {
            do {
                let realm = try Realm()
                let deviceContacts = Array(realm.objects(DeviceContactModel.self).filter("ANY phones.fullNumber IN %@", phoneNumbers))
                return deviceContacts
            } catch {
                debugPrint(error.localizedDescription)
                return []
            }
        }

答案 1 :(得分:0)

你可以使用:

var numbers: [[DeviceContactModel]] = [[]]
for number in phoneNumbers{
   let deviceContacts = Array(realm.objects(DeviceContactModel.self))
   let deviceWithNumber = deviceContacts.filter({ $0.fullNumber == number })
   numbers.append(deviceWithNumber)
}
return numbers.flatMap({ $0 })