Subclassing NSArrayController causes objects from ManagedObjectContext doesn't show in NSTableView

123 Views Asked by At

That's very strange. I have a Model with three Entities. Like this: enter image description here

In InterfaceBuilder I made NSArrayController connected to MOC via RepresentedObject to ViewController. Everything works, I can add and delete Master objects, select them, I can bind to TableView and edit them. But if I subclass NSArrayControler to MasterController and add just observer:

class MastersController: NSArrayController {

override func awakeFromNib() {
    self.addObserver(self, forKeyPath: "selection", options: NSKeyValueObservingOptions.old, context: nil)
}

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    Swift.print("observing", keyPath ?? "<no path>")
    switch keyPath! {
    case "selection":
        Swift.print("selection Changed")
    default: break

    }
}

TableView doesn't see already existing objects, only just added. I can edit them. But when I open the document again newly added objects disappear too. If I will change the class of controller back to NSArrayController I can see them all again.

Any help?

2

There are 2 best solutions below

3
Matusalem Marques On

I'm almost sure observeValue(forKeyPath:of:change:context:) is used internally by NSArrayController and you should call super.observeValue(forKeyPath:of:change:context:) to get the expected behaviour...

0
Łukasz On

The problem was solved by calling super.awakeFromNib() in overrided func awakeFromNib()