How to integrate Realm Objects into NSArrayController & NSTableView


#1

I am currently working on a macOS application that uses CoreData for persistence. I would like to replace CoreData with Realm but I cannot find any integration of NSArrayController with Realm entities when it comes to displaying the objects to an NSTableView. Obviously CoreData allows the NSTableView+NSArrayController to work quite nicely.

Is there anyway to have a similar setup with Realm entities?


#2

You should be able to just bind the NSArrayController contents to an Array(Results). If you are using bindings for field level updates you need to override the RealmObjects setValue() function like this

@objc public override func setValue(_ value: Any?, forKey key: String) {
        // make sure we begin a write transaction if this is a managed object
        self.realm?.beginWrite()
        
        // actually do the update
        super.setValue(value, forKey: key)
        
        // commit the write transaction if managed
        // this will crash if the write fails, in the real world you'd want to use do { } catch { }
        try! self.realm?.commitWrite()
    }

#3

I am just trying to figure out how to use the NSArrayControllers add() method to create new objects - currently it works but the objects are not persisted in Realm - so I am guessing I need to subclass the add() method to add the new object to the Ream store.