0

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?

Arghavan
  • 1,125
  • 1
  • 11
  • 17
Łukasz
  • 773
  • 5
  • 23
  • 1
    At least it's good habit to check for key path or context and call super if the check does not succeed. – vadian Jun 21 '17 at 10:45
  • Colud You explain? I'm type designer :) Key path of what exactly? Could changing class change context or some key path? – Łukasz Jun 21 '17 at 10:49
  • 1
    Probably it's not related to the issue but methods like `observeValue(forKeyPath` are supposed to call super if the affected key path or the context don't match the observer of the current class. If you don't call super the super class does not respond to that method – vadian Jun 21 '17 at 10:55
  • Problem was solved by super.awakeFromNib. Thank You! – Łukasz Jun 21 '17 at 11:05
  • Why do you want to subclass `NSArrayController`? – Willeke Jun 21 '17 at 20:53
  • To add @IBAction addMaster(_ sender:Any) based on selection in another Controller. I don't know how to do it in another way. – Łukasz Jun 23 '17 at 12:20
  • Use an extension. – Willeke Jun 23 '17 at 21:02
  • May I add @IBOutlet to extension? – Łukasz Jun 25 '17 at 13:08

2 Answers2

1

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...

Matusalem Marques
  • 2,399
  • 2
  • 18
  • 28
0

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

Łukasz
  • 773
  • 5
  • 23