Search code examples
swiftmacoscore-datatableviewnsarraycontroller

How to sort NSTableView with NSArrayController programmatically?


I have a NSTableView with just one column but different values in subviews. The tableView is populated by NSArrayController which is bound to a CoreData entity. I was wondering how to sort the tableView by custom buttons.

class ViewController: NSViewController {

   @IBOutlet var arrayController: NSArrayController!

   @IBAction func sortByName(_ sender: Any) {

       arrayController.sort... ?
   }

   @IBAction func sortByAge(_ sender: Any) {

       arrayController.sort... ?

   }

}

I know how to make NSArrayController to sort the columns by clicking on the row header. But since I have only one column but different values, I´m trying to find a way to sort by custom buttons. Any help would be much appreciated.


Solution

  • Set the sortDescriptors property of the array controller and call arrayController.rearrangeObjects()

    class ViewController: NSViewController {
    
        @IBOutlet var arrayController: NSArrayController!
    
        @IBAction func sortByName(_ sender: Any) {
            sortArrayController(by: "name")
        }
    
        @IBAction func sortByAge(_ sender: Any) {
            sortArrayController(by: "age")
        }
    
        func sortArrayController(by key : String) {
            arrayController.sortDescriptors = [NSSortDescriptor(key: key, ascending: true)]
            arrayController.rearrangeObjects()
        }
    
    }