swiftrealmrealm-cocoa

Swift diff realm.io without fetching it in advance


I was wondering if there is a possibility in realm.io (swift) to select all items from one "table" that are not in the other one.

Lets say you have 2 classes:

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
}

Is it possible to get an result of items from A who's id is not present in B?


Solution

  • There is actually a very simple way to do this using NSPredicate on Realm filter API.

    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 { $0.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 { $0 }
            } catch {
    
                // Throw an error if any
                throw error
            }
    
    }
    

    Also note that all objects from fetched using Realm are lazy loaded which means that this method is also very fast. From the documentation:

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