Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting NSTableView

I have two coloumn in NSTableView as Name and Salary with 5-10 values. I want to sort these coloumn after click on header of both the column. There is lots of data present in Internet but I am not able to use these. Please help me to do this in cocoa.

Thanks in advance and appreciate any help.

like image 365
upender Avatar asked Jun 19 '12 06:06

upender


1 Answers

Each table column has a method setSortDescriptorPrototype Sort descriptors are ways of telling the array how to sort itself (ascending, descending, ignoring case etc.) Iterate over each of the columns you want as sortable and call this method on each of those columns, and pass the required sort descriptor (In my case I'll be using 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 that notifies you whenever a sort descriptor is changed, implement this method in the data source and send a message to the data array to sort itself

- (void)tableView:(NSTableView *)aTableView sortDescriptorsDidChange:(NSArray *)oldDescriptors
{
    self.data = [self.data sortedArrayUsingDescriptors:sortDescriptors];
    [aTableView reloadData];
}

This method will get fired each time a column header is clicked, and NSTableColumn shows a nice little triangle showing the sorting order.

like image 116
rounak Avatar answered Oct 30 '22 16:10

rounak