Sorting NSTableView - cocoa

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.

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.

I stumbled upon this question while looking for the easiest way of implementing something similar. Although the original question is old, I hope someone finds my answer useful! Please note that I am using Xcode 5.1.1
Ok so to do this you need to:
select the actual column you want to sort in your table.
In your Attributes Inspector you need to fill in two fields: Sort Key, and Selector.
In the Sort Key field, you need to enter the value of your Identifier. The value of your Identifier is located in your Identity Inspector.
In the Selector field you need to enter a suitable selector method based on the object type in the column. The default method is; compare:
Based on the Table View Programming Guide for Mac. The compare: method works with NSString, NSDate, and NSNumber objects. If your table column contains only strings, you may want to consider using the caseInsensitiveCompare: method if case sensitivity is unimportant. However, consider replacing these method signatures with the localizedCompare: or localizedCaseInsensitiveCompare: methods to take into the account the user’s language requirements.
Finally, you need to declare the tableView:sortDescriptorsDidChange: method in your Table View Controller in the format shown below:
-(void)tableView:(NSTableView *)mtableView sortDescriptorsDidChange:(NSArray *)oldDescriptors
{
[listArray sortUsingDescriptors: [mtableView sortDescriptors]];
[tableView reloadData];
}

Just had lately the same issue to get tableView sorted.
My approach :
bind your sortDescriptors to tableview's arrayController
bind tableview's sortDescriptors to Arraycontroller's sort descriptor
perform the settings in attribute inspector (see Tosin's answer above)
Worked perfect for me. No need to set prototypes for columns or something else.

Thanks very much ,It is usefullly for my question.
my code like this
First, set unique values in the XIB interface,like name...
- (void)viewDidLoad {
[super viewDidLoad];
self.itemTableView.dataSource = self;
self.itemTableView.delegate = self;
self.itemTableView.selectionHighlightStyle = NSTableViewSelectionHighlightStyleRegular;
self.itemTableView.usesAlternatingRowBackgroundColors = YES;
for (NSTableColumn *tableColumn in self.itemTableView.tableColumns ) {
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:tableColumn.identifier ascending:NO selector:#selector(compare:)];
[tableColumn setSortDescriptorPrototype:sortDescriptor];
}
}
-(void)tableView:(NSTableView *)tableView sortDescriptorsDidChange:(NSArray<NSSortDescriptor *> *)oldDescriptors{
NSLog(#"sortDescriptorsDidChange:%#",oldDescriptors);
[self.itemArr sortUsingDescriptors:[tableView sortDescriptors]];
[self.itemTableView reloadData];
}

Related

How to sort NSTableView in Swift using sortDescriptors?

I use view-based NSTableView in my Cocoa app which is written in Swift, and want to implement a sort functionality on two table columns. However, in Objective-C, you can implement it by first setting the "Sort Key" in Attribute Inspector, and then implement the data source delegate method named tableView: sortDescriptorsDidChange:.
However, this method takes sortDescriptor as a parameter and lets developers use it within the method, like so:
- (void) tableView:( NSTableView *) tableView sortDescriptorsDidChange:( NSArray *) oldDescriptors {
[self.songs sortUsingDescriptors:tableView.sortDescriptors];
[tableView reloadData];
}
However, in Swift Array, there are no such method as sortUsingDescriptors. So I first tried to convert Array to NSMutableArray in order to use the NSMutableArray's method, but since my Swift Array is defined as AnyObject[], it cannot be casted to NSMutableArray.
So how should I implement the sort functionality to the table view in Swift? I know Swift Array can use sort function to sort the object by comparing the two arguments and returning bool values, but is it possible to use sortDescriptors to sort the table? Or should I just ignore the sortDescriptors argument and instead write my own sort logic manually? (but then I don't know how to tell what column is clicked without the sortDescriptors value).
Probably the best way, at least right now, is to first convert it to NSMutableArray and then sort it using NSMutableArray's sortUsingDescriptors method, and finally convert it back to the original Array, like so:
func tableView(tableView: NSTableView!, sortDescriptorsDidChange oldDescriptors: [AnyObject]) {
var songsAsMutableArray = NSMutableArray(array: songs)
songsAsNSMutableArray.sortUsingDescriptors(tableView.sortDescriptors)
songs = songsAsNSMutableArray
tableView.reloadData()
}
By the way, var songsAsMutableArray = songs as NSMutableArray causes an error: NSArray is not a subtype of NSMutableArray, so I created an NSMutableArray instance as shown above.

Getting a column in an NSTableView with editable column order

I have an NSTableView where I would like to be notified if the user clicks in a column "ClickMe". I linked the entire table view to a method which can extract the clickedColumn:, but I get an absolute number and not a reference to the "ClickMe" column (which may have been moved to another place).
I could of course program my own search algorithm to see if column X is actually the "Clickme" column, but that would not be very elegant. Is there a way to identify columns properly, and to receive that ID programmatically?
I found a way to do my own search in a fairly fast way, but I still have a feeling I am putting too much effort in this:
First, set the Identifier of the desired column in the Interface Builder to "ClickMeColumn". Then:
NSInteger cmColumn = [tableView columnWithIdentifier:#"ClickMeColumn"];
if ( [tableView clickedColumn] == cmColumn )
NSLog(#"Clicked me!");
I am looking for something along the lines of [tableView clickedColumnIdentifier].
What about querying NSTableView's columnAtPoint: in your table views mouseDown: or mouseUp: method?
Use any of the methods below. Called by the tableView's delegate on selection. You can extract the identifier and the title string from the relevant tableColumn.
- (void)tableView:(NSTableView *)tableView didClickTableColumn:(NSTableColumn *)tableColumn {
NSLog(#"tableView:didClickTableColumn: %#, titleString: %#", [tableColumn identifier], [[tableColumn headerCell] stringValue]);
}
- (void)tableView:(NSTableView *)tableView mouseDownInHeaderOfTableColumn:(NSTableColumn *)tableColumn {
NSLog(#"tableView:mouseDownInHeaderOfTableColumn: %#, titleString: %#", [tableColumn identifier], [[tableColumn headerCell] stringValue]);
}
From: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSTableView_Class

Setting and maintaining the first SortDescriptor for an NSTableView

I have an NSTableView with columns bound to an NSArrayController.
The table view shows a list of email messages:
Flag if unread
Subject
Attachment size
The user can click on the Attachment Size column to sort the list, but I would like the table to always be sorted by the "unread" flag first so that the unread messages always remain at the top of the list.
I did not bind the Array Controller's sort descriptors to anything, yet table sorting works magically by clicking on the table columns (why?). Is there some way I can intercept setting the Array Controller's sort descriptors and insert the "Unread" sort descriptor first?
Example of a table sorted by attachment size:
UNREAD▼ SUBJECT ATTACHMENT SIZE▼
------ ------- ------------------
yes Hello.. 110kb
yes Test... 90kb
no Foobar 200kb
no Hey 100kb
no Test2 10kb
Well, the reason it "just works" is because the table columns call setSortDescriptors: on their bound NSArrayController.
Assuming you want the table to remain sortable, but you always want to sort by "unread", this is how I would go about it:
First, subclass NSArrayController and override arrangeObjects:
- (NSArray *)arrangeObjects:(NSArray *)objects {
NSMutableArray *oldSorted = [[super arrangeObjects:objects] mutableCopy];
NSMutableArray *newSorted = [NSMutableArray arrayWithCapacity:[oldSorted count]];
for (id anObject in oldSorted)
if ([[anObject valueForKey:#"isUnread"] boolValue])
[newSorted addObject:anObject];
[oldSorted removeObjectsInArray:newSorted];
[newSorted addObjectsFromArray:oldSorted];
[oldSorted release];
return newSorted;
}
This puts unread messages at the "top" (beginning of array). I'm not sure this is the most efficient sorting algorithm, but I believe it's the correct way to go about it.
I think that you can just set an array of sortDescriptors on your array controller during awakeFromNib. No need to force arrangeObjects:, this functionality totally built in.
- (void)awakeFromNib {
[super awakeFromNib];
NSSortDescriptor *unreadSorter = [[NSSortDescriptor sortDescriptorWithKey:#"isUnread" ascending:NO)] autorelease];
NSArray *arrayOfSortDescriptors = [NSArray arrayWithObject:unreadSorter];
[self setSortDescriptors:arrayOfSortDescriptors];
}
The columns will still remain sortable when you click the column header.

View Based Table Cells on OS X not showing data properly

So I admit to being a total noob to cocoa, so I offer a noob question. I'm probably just missing the dumb obvious somewhere but i just cant seem to get my table to populate data.
I'm following the table view playground example but everytime i try to mimic the Basic TableView Window the first row becomes the height of the number of rows i added (at least thats what it looks like. Here is my code:
- (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row
{
NSString *identifier = [tableColumn identifier];
if ([identifier isEqualToString:#"filename"]) {
// We pass us as the owner so we can setup target/actions into this main controller object
NSTableCellView *cellView = [fileBrowserTable makeViewWithIdentifier:identifier owner:self];
// Then setup properties on the cellView based on the column
cellView.textField.stringValue = [fileList filenameAtIndex:row];
cellView.imageView.objectValue = [[NSWorkspace sharedWorkspace] iconForFile:[fileList fullPathAtIndex:row]];
return cellView;
}
else if ([identifier isEqualToString:#"path"]) {
NSTextField *textField = [fileBrowserTable makeViewWithIdentifier:identifier owner:self];
textField.objectValue = [fileList pathAtIndex:row];
return textField;
}
else if ([identifier isEqualToString:#"preview"]) {
NSTextField *textField = [fileBrowserTable makeViewWithIdentifier:identifier owner:self];
textField.objectValue = [fileList previewAtIndex:row];
return textField;
}
return nil;
}
I think its worth mentioning that when using a the old school text field cell, I have no problems displaying data (of course the above code is different in that case) so im positive sure its not a problem with my data structure that holds the values. I have also set the correct delegate and data source
The cell using the 'filename' identifier uses the 'image and text table view cell' while the others use just a 'text table cell view'. Neither of them work so i'm guessing something is wrong with how I set my table up. But when comparing my table with that of the example, it's just a spitting reflection (minus identifiers file names).
One thing that I notice that I can't quite figure out is that the example says:
The NSTableView has two reuse identifier assocations: "MainCell" and "SizeCell" are both associated with the nib ATBasicTableViewCells.xib
I don't really understand this statement. However that being said, the example doesn't contain any ATBasicTableViewCells.xib nor does it have any associations with it (code or ib) that I can find.
Have you tried to set the rowSizeStyle of the NSTableView to NSTableViewRowSizeStyleCustom?
[UPDATE] Re-reading your question, it's not clear for me what your problem is. The solution I have given is related to problems with the size of each cell which is not taken into account unless the rowSizeStyle is set to custom.

Binding to NSTextField Cell not working, edited value resets to default

I'm working on a Core Data document application that dynamically creates NSTableColumns. The data cell type may be a checkbox, slider, etc. Programmatically binding to all cell types works, except for NSTextFieldCell.
All NSTextFieldCells fail to bind, and after editing they return to their default value. This happens no matter if they're binding to a string, a number (with an NSNumberFormatter applied), or a date (NSDateFormatter applied). I'm using the following format to do all bindings:
NSDictionary *textFieldOpts = [NSDictionary dictionaryWithObjectsAndKeys:#"YES", NSContinuouslyUpdatesValueBindingOption, #"YES", NSValidatesImmediatelyBindingOption, nil];
[aCell bind:#"value" toObject:[[entryAC arrangedObjects] objectAtIndex:0] withKeyPath:#"numberData" options:textFieldOpts];
Again, these statements work if the cell type is anything but an NSTextFieldCell.
I threw in an -observeValueForKeyPath method to log when the value changes... and for other cell types (NSSliderCell for instance) I can see the value changing, but with the NSTextFieldCell, it never, ever updates.
Turns out that I needed to implement the NSTableView data source method setObjectValue to manually get the change from the NSTableView (View) and then manually set the data in the array controller (Model) similar to the code below:
- (void)tableView:(NSTableView *)aTableView setObjectValue:(id)anObject forTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex {
[[[entryAC arrangedObjects] objectAtIndex:rowIndex] setValue:(NSNumber *)anObject forKey:#"numberData"];
}
For some reason, the bindings to NSTextFieldCells, when set programmatically on a cell-by-cell basis, only work one way: to display the data only. Personally I would classify this as a bug...

Resources