How to get selected item of NSOutlineView without using NSTreeController?

@Dave De Long: excellent answer, here is the translation to Swift 3.0

@objc private func onItemClicked() {
    if let item = outlineView.item(atRow: outlineView.clickedRow) as? FileSystemItem {
        print("selected item url: \(item.fileURL)")
    }
}

Shown is a case where item is from class FileSystemItem with a property fileURL.


NSOutlineView inherits from NSTableView, so you get nice methods such as selectedRow:

id selectedItem = [outlineView itemAtRow:[outlineView selectedRow]];

Swift 5

NSOutlineView has a delegate method outlineViewSelectionDidChange

 func outlineViewSelectionDidChange(_ notification: Notification) {

    // Get the outline view from notification object
    guard let outlineView = notification.object as? NSOutlineView else {return}

    // Here you can get your selected item using selectedRow
    if let item = outlineView.item(atRow: outlineView.selectedRow) {
      
    }
}

Bonus Tip: You can also get the parent item of the selected item like this:

func outlineViewSelectionDidChange(_ notification: Notification) {

// Get the outline view from notification object
guard let outlineView = notification.object as? NSOutlineView else {return}

// Here you can get your selected item using selectedRow
if let item = outlineView.item(atRow: outlineView.selectedRow) {
  
     // Get the parent item
      if let parentItem = outlineView.parent(forItem: item){
            
      }  
   } 
}

Tags:

Cocoa

Pyobjc