user3722523 user3722523 - 3 months ago 34
Swift Question

Always sort NSTableView

How I can always sort a column in NSTableView ?
when my view is loaded the data isn't sorted and also when the data is updated. For now only when I click on the header column the data is sort.

Here is my code to sort the data when clicking on the header column :

In ViewDidLoad :

let descriptorName = NSSortDescriptor(key: "designation", ascending: true, selector: #selector(NSString.caseInsensitiveCompare(_:)))
tableview.tableColumns[0].sortDescriptorPrototype = descriptorName

The delegate func :

func tableView(_ tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) {
let dataArrayMutable = NSMutableArray(array:
dataArrayMutable.sort(using: tableView.sortDescriptors) = (dataArrayMutable as NSArray) as! [Article]

Problem solved : I had to sort the data in the data Array before loading the tableView. Here is the code :

data = data.sorted(by: { $0.designation! < $1.designation! })


The order of the elements in your data source dictates the order of the elements in the table view. That's why, when your data source (not your delegate, technically) gets told that the sort descriptors have changed, what you do is change the order of the data that the data source manages.

So, the answer to your question is just to keep the data source's data in the desired order from the start. Don't just sort it in tableView(_:sortDescriptorsDidChange:). Sort it from the start.

Of course, if you add data dynamically, you need to maintain the sort order. You can use index(of:inSortedRange:options:usingComparator:) to find where to insert a new element to maintain the sort order. Or, you can just add the data anywhere and then sort again.