Pregunta

One can put an observer on the selectedIndex method of NSArrayController. This method has some drawbacks I think :

  • what will happen when the arrangedObjects is rearranged ? I admit this is not a very important problem

  • if we ask the observer to remember the old value of selectedIndex, it doesn't work. It is known but I cannot find again the link.

Why doesn't NSArrayController have a delegate ? Is there another way to achieve what I want to do : launching some methods when the selection changes ?

¿Fue útil?

Solución

Observe selection key of the NSArrayController (it is inherited from NSObjectController).

It will return either NSMultipleValuesMarker (when many objects are selected), NSNoSelectionMarker (when nothing is selected), or a proxy representing the selected object which can then be queried for the original object value through self key.

It will not change if rearranging objects did not actually change the selection.

You can also observe selectedObjects; in that case you won't need to deal with markers.

Otros consejos

Providing hamstergene's excellent solution, in Swift 4.

In viewDidLoad, observe the key path.

arrayController.addObserver(self, forKeyPath: "selectedObjects", options: .new, context: nil)

In the view controller,

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    guard let keyPath = keyPath else { return }

    switch keyPath {

    case "selectedObjects":
        // arrayController.selectedObjects has changed

    default:
        break
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top