Swift diff realm.io 没有提前获取

Swift diff realm.io without fetching it in advance

我想知道是否有可能 realm.io (swift) 到 select 一个 "table" 中不在另一个 "table" 中的所有项目。

假设你有 2 个 类:

class A: Object {
    dynamic var id: Int = 0
    dynamic var text: String = ""
}

class B: Object {
    dynamic var id: Int = 0
    dynamic var value: Bool = false
}

是否可以从 A 中获取其 ID 在 B 中不存在的项目的结果?

在 Realm 过滤器 API.

上使用 NSPredicate 实际上有一个非常简单的方法可以做到这一点
func fetch() throws -> [A] {
        do {
            // Create Realm
            let realm = try Realm()

            // Get B objects from Realm and put their IDs to [Int] array
            let IdB: [Int] = realm.objects(B).map { [=10=].id }

            // Create predicate
            // Filter all items where property id is not present in array IdB
            let predicateFilter = NSPredicate(format: "NOT (id IN %@)", IdB)

            // Get all A objects from array using predicateFilter
            let objectsA = realm.objects(A).filter(predicateFilter)

            // Return the [A] array
            return objectsA.map { [=10=] }
        } catch {

            // Throw an error if any
            throw error
        }

}

另请注意,使用 Realm 获取的所有对象都是延迟加载的,这意味着此方法也非常快。来自文档:

All queries (including queries and property access) are lazy in Realm. Data is only read when the properties are accessed.