Each table column has a setSortDescriptorPrototype method. setSortDescriptorPrototype descriptors are ways to tell the array how to sort itself (ascending, descending, case-insensitive, etc.) Iterate over each column that you want to sort, and call this method for each of these columns and pass the required sort descriptor (in my case, I will use the column identifier)
for (NSTableColumn *tableColumn in tableView.tableColumns ) { NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:tableColumn.identifier ascending:YES selector:@selector(compare:)]; [tableColumn setSortDescriptorPrototype:sortDescriptor]; }
After writing this piece of initialization code, NSTableViewDataSource has a method - (void)tableView:(NSTableView *)aTableView sortDescriptorsDidChange:(NSArray *)oldDescriptors , which notifies you of every change to the sort descriptor, implements this method in the data source, and sends a message to the data array to sort yourself
- (void)tableView:(NSTableView *)aTableView sortDescriptorsDidChange:(NSArray *)oldDescriptors { self.data = [self.data sortedArrayUsingDescriptors:sortDescriptors]; [aTableView reloadData]; }
This method works every time you click on the column heading, and NSTableColumn shows a nice little triangular button showing the sort order.
rounak
source share