TweetFollow Us on Twitter

Takes All Sorts

Volume Number: 18 (2002)
Issue Number: 8
Column Tag: Mac OS X

Takes All Sorts

Make Your TableViews Autosort!

by Andrew C. Stone

One of the coolest pieces of object technology in the Cocoa bag of tricks is the NSTableView, and its daughter, NSOutlineView. The tableView lets you display a list of items with various properties. As in a spreadsheet, it displays rows of information - anything from simple text to graphics or even quicktime movies! Once you learn the fundamentals of the tableView and the outlineView, they'll quickly become some of your favorite user interface objects.

This article will take the NSTableView further, and show you how to add "auto sort" to your tableView, and the objects it represents. It assumes you have read the documentation for NSTableView and its companion class NSTableColumn and perhaps already have an app with an NSTableView of your own. You can try out this sort idea in Apple's Mail. A Mail Box shows a tableView of the list of messages, sender, subject, date, size, etc:


Figure 1. You can play with quick sort feature in Apple's Mail application.

When you click on the title cell of a column, an arrow appears to show direction of the sort, the cell is highlighted, and the messages are sorted on that key. If you click the title cell of that same column again, it toggles the sort to reverse its direction: if it was an ascending sort, now it's a descending sort. Sorting mail by subject is particularly interesting for deleting spam en masse!

When Time Equals Money...

When preparing TimeEqualsMoney 2.0 <http://www.stone.com/TimeEqualsMoney/> this spring, I decided users would love to be able to sort their time and expense entries on any key, in either direction with a simple click. So I reread the documentation Apple provides on the NSTableView class. I highly recommend actually reading the .h files! It's amazing how much stuff is already anticipated for you! There is a delegate method, - (void) tableView:(NSTableView*)tv didClickTableColumn:(NSTableColumn *)tableColumn. So, it seemed, I simply had to implement this method in my NSWindowController subclass, which is architecturally a sound choice for the NSTableView delegate. However, the method was simply not being called when I clicked on the column header cell. It turns out, and I noted this heavily in my code, that if neither column reodering nor column selection is selected in Interface Builder's NSTableView inspector, then the method is not called. Turning on column reordering was a simple fix and a desired feature! You can, of course, also call one of these methods programmatically with a parameter of YES:

- (void)setAllowsColumnReordering:(BOOL)flag;
- (void)setAllowsColumnSelection:(BOOL)flag;

Following on the Model-View-Controller pattern that I have discussed in previous articles on Cocoa architecture, I decided to store the sort column, and its direction in my NSDocument subclass, as well as make it responsible for the sorting of its items. This way, you can undo the sort, automatically mark the document as unsaved as well as save the sort between sessions. The user clicks the tableView column header, the window controller then sets the document's sort key, or direction if the key was already set to that column. Then the document tells itself to sort, which tells its NSMutableArray of entries to sort its contents. Finally, the document tells its window controllers to reload the tableView, which updates the interface to display the new sort order:


Figure 2. This tableView lets you click a column header to sort on that key - up or down.

Model Behavior

The implementation of the actual sort is trivial: just ask the list to sort itself based on asking its elements to sort using a selector: [list sortUsingSelector:@selector(compare:)];

During the list's sorting procedure, it repeatedly calls, in this case, compare: on one list item against another.

I like to just reuse the Kit's compare: which is implemented in NSString, NSDate, NSCell, NSValue, etc:

- (NSComparisonResult)compare:(id)other;

The NSComparisonResult has these three values: NSOrderedAscending = -1, NSOrderedSame = 0, NSOrderedDescending = 1. Since so many objects reply to compare:, you might implement it something like this in your data object, given that the sort key is the same string as the column identifiers, and you have various numbers, dates, strings and even booleans:

// the Data MODEL - the document has a list of these entities:
@interface PieceWork : NSObject <NSCopying>
{
    NSCalendarDate *startTime;
    NSString *description;
    NSTimeInterval timeOnJob;
    float _rate;
    BOOL paid;
    id owner;
...
}
- (NSComparisonResult)compare:(id)other;
- (void)setOwner:(id)ownsMe;
- (NSCalendarDate *)startTime;
- (NSTimeInterval)timeOnJob;
- (NSString *)workDescription;
- (float)hoursOnJob;
- (float)rate;
- (BOOL)paid;
...
@end
@implementation PieceWork
...
- (NSComparisonResult)compare:(id)other {
    BOOL isDescending = [owner sortIsDescending];
    NSString *key = [owner sortColumn];
   // now determine which one is first based on sort direction:
    PieceWork *first = isDescending ? other : self;
    if (first == other) other = self;
    
    if ([key isEqualToString:@"TimeOnJob"]) {
        return [[NSNumber numberWithFloat:[other timeOnJob]] compare: 
        [NSNumber numberWithFloat:[first timeOnJob]]];
    } else if ([key isEqualToString:@"Date"]) {
        return [[other startTime] compare: [first startTime]];
    } else if ([key isEqualToString:@"Description"]) {
// Very handy macro:
#define IS_NULL(s) (!s || [s isEqualToString:@""])
            if (IS_NULL([other workDescription])) return NSOrderedDescending;
            if (IS_NULL([first workDescription])) return NSOrderedAscending;
// people prefer upper and lower case mixed, unlike UNIX:
        return [[other workDescription] caseInsensitiveCompare:[first workDescription]];
    } else if ([key isEqualToString:@"Paid"]) {
        return [[NSNumber numberWithBool:[other paid]] compare:[NSNumber 
        numberWithBool:[first paid]]];
    }
    return 0;
}
@end

Here are the relevant instant variables and methods in the NSDocument subclass:

@interface MyDocument : NSDocument {
    NSMutableArray *_workList;
    NSString *_sortColumn;
    BOOL _sortIsDescending;
.   ...
}
- (void)sort;
- (NSArray *)workList;
- (void)setSortColumn:(NSString *)identifier;
- (NSString *)sortColumn;
- (void)setSortIsDescending:(BOOL)whichWay;
- (BOOL)sortIsDescending;
...
@end
@implementation MyDocument
...
- (void)sort:(NSMutableArray *)list {
    [list makeObjectsPerformSelector:@selector(setOwner:) withObject:self];
    [list sortUsingSelector:@selector(compare:)];  // asks us for how!!
}
- (void) sort {
    if (NOT_NULL(_sortColumn)) {
        [self sort:_workList];
        [[self windowControllers] makeObjectsPerformSelector:@selector(updateTotalsAndReload)];
    }
}
- (void)setSortColumn:(NSString *)identifier {
    if (![identifier isEqualToString:_sortColumn]) {
        [[[self undoManager] prepareWithInvocationTarget:self] setSortColumn:_sortColumn];
    [_sortColumn release];
    _sortColumn = [identifier copyWithZone:[self zone]];
        [[self undoManager] setActionName:NSLocalizedStringFromTable(@"Sort",@"TimeCard",@"title of 
        undo the sort action")];
    }
}
- (NSString *)sortColumn {
    return _sortColumn;
}
- (void)setSortIsDescending:(BOOL)whichWay {
    if (whichWay != _sortIsDescending) {
        [[[self undoManager] prepareWithInvocationTarget:self] setSortIsDescending:_sortIsDescending];
    _sortIsDescending = whichWay;
        [[self undoManager] setActionName:NSLocalizedStringFromTable(@"Sort 
        Direction",@"TimeCard",@"title of undo the sort up or down action")];
    }
}
- (BOOL)sortIsDescending {
    return _sortIsDescending;
}
- (NSArray *)workList { return _workList; }
- (void)setWorkList:(NSMutableArray *)list {
    [[[self undoManager] prepareWithInvocationTarget:self] setWorkList:_workList];
    [_workList release];
    if (NOT_NULL(_sortColumn)) [self sort:list];
    _workList = [list mutableCopyWithZone:[self zone]];
    [_workList makeObjectsPerformSelector:@selector(setOwner:) withObject:self];
    [[self windowControllers] makeObjectsPerformSelector:@selector(updateTotalsAndReload)];
    [[self undoManager] setActionName:NSLocalizedStringFromTable(@"Work Change", @"TimeCard", 
    @"Action name for changing worklist")];
}
// And don't forget to actually archive and read the sort info
// I highly recommended using human readable XML dictionaries:
- (NSMutableDictionary *)workDocumentDictionary {
    NSMutableDictionary *doc = [NSMutableDictionary dictionary];
        unsigned i, c = [_workList count];
        if (NOT_NULL(_sortColumn)) [doc setObject:_sortColumn forKey:SortNameKey];
        if (_sortIsDescending) [doc setObject:@"YES" forKey:SortDescendingKey];
       ...
       return doc;
}
- (BOOL)loadDataRepresentation:(NSData *)data ofType:
                                                      (NSString *)type {
    if ([type isEqualToString:DocumentType]) {
 NSDictionary *doc = [self workDocumentDictionaryFromData:data];
        id obj;
        ...
        obj = [doc objectForKey:SortNameKey];
        if (obj) {
            [self setSortColumn:obj];
        }
      obj = [doc objectForKey:SortDescendingKey];
        if (obj) {
            _sortIsDescending = [@"YES" isEqualToString:obj];
        }
        return YES;
  }
  return NO;
}
@end

Control Freak

Finally, we come to the meat of the matter in our NSWindowController subclass which is our NSTableView's dataSource as well as delegate.

@interface JobWindowController : NSWindowController 
{
    IBOutlet NSTableView *tableView;
    NSImage *descendingSortingImage;
    NSImage *ascendingSortingImage;
    ...
}

We have work to do in our window initialization method that gets called when the Interface has loaded, awakeFromNib. We want to get the images that we shall display when a sort is made. Using class-dump as described in my iPhoto Exporter bundle article <http://www.omnigroup.com/~nygard/Projects/index.html>, you might note that there are hidden, private Apple internal API to access the images to indicate ascending or descending sorts! Since one should absolutely never rely on hidden API to not dissolve into the ether in subsequent system releases, always bracket the use of these methods with a "respondsToSelector:" query, and provide backup images of your own:

- (void)awakeFromNib
{
    // private images:
    if ([[NSTableView class] respondsToSelector:@selector(_defaultTableHeaderSortImage)])
    ascendingSortingImage = [[NSTableView class] _defaultTableHeaderSortImage];
    else ascendingSortingImage = [[NSImage imageNamed:@"ascendingSort"] retain];
    if ([[NSTableView class] respondsToSelector:@selector(_defaultTableHeaderReverseSortImage)])
    descendingSortingImage = [[NSTableView class] _defaultTableHeaderReverseSortImage];
    else descendingSortingImage = [[NSImage imageNamed:@"descendingSort"] retain];
...
}

If you allow users to move and resize columns, then you definitely want to additionaly call these two methods in awakeFromNib - this will reestablish their preferences and give the system a name to save the column order and sizes.

    [tableView setAutosaveTableColumns:YES];
    [tableView setAutosaveName:@"WorkTable"];
    

So, now we're ready to implement the delegate method which gets called when the column title cell is clicked. The one fine point is that we want to make a note of which item was selected before the sort, so we can reselect it after the sort (its row number may have changed after the sort). We ask the tableView if it already has an image in that column, thus indicating that we need to toggle the direction, otherwise, we'll set the new sort key. The actual work of setting up the tableView's header hilighting is done in updateTableHeaderToMatchCurrentSort. This is factored into a separate method so we can also call it when loading a document to restore last saved sort state.

// BIG COCOA NOTE: if column reordering or column selection is not on
// then this doesn't get called!!
- (void) tableView:(NSTableView*)tv didClickTableColumn:(NSTableColumn *)tableColumn {
    NSImage *sortOrderImage = [tv indicatorImageInTableColumn:tableColumn];
    NSString *columnKey = [tableColumn identifier];
    MyDocument *doc = [self document];
    PieceWork *work = [self selectedWork];
    // If the user clicked the column which already has the sort indicator
    // then just flip the sort order.
    
    if (sortOrderImage || columnKey == [doc sortColumn]) {
        [doc setSortIsDescending:![doc sortIsDescending]]; 
    } else {
        [doc setSortColumn:columnKey];
    }
    [self updateTableHeaderToMatchCurrentSort];
    // now do it - doc calls us back when done
    [doc sort];
    // but reselect the one previously selected:
    if (work) [self selectWork:work];
}

This method updates the state of the NSTableColumn by first clearing all cells, and then setting the correct image and hilighting on the column to sort by, if any:

- (void)updateTableHeaderToMatchCurrentSort {
    BOOL isDescending = [[self document] sortIsDescending];
    NSString *key = [[self document] sortColumn];
    NSArray *a = [tableView tableColumns];
    NSTableColumn *column = [tableView tableColumnWithIdentifier:key];
    unsigned i = [a count];
    
    while (i-- > 0) [tableView setIndicatorImage:nil inTableColumn:[a objectAtIndex:i]];
    
    if (NOT_NULL(key)) {
        [tableView setIndicatorImage:(isDescending ? ascendingSortingImage:descendingSortingImage) 
        inTableColumn:column];
        
        [tableView setHighlightedTableColumn:column];
    } else [tableView setHighlightedTableColumn:nil];
}

And our helper functions to make the code neat and compact:

- (NSArray *)workList {
   return [[self document] workList];
}
- (void)updateTotalsAndReload {
// other ui:
//    [self updateTotals];
    [tableView reloadData];
}
- (PieceWork *)selectedWork {
   NSArray *workList = [self workList];
   int row = [tableView selectedRow];
   if (row > -1 && row < [workList count]) return [workList objectAtIndex:row];
   return nil;
}
- (void)selectWork:(PieceWork *)work {
    NSArray *a = [self workList];
    unsigned i = [a indexOfObject:work];
    if (i != NSNotFound) [self selectRow:i];
}

Devil in the Details

So, now we got sorting working, what sort of problems might we run into? Let's say a user edits the field of an entry in the sorted column. Upon finishing editing, they may have changed the relative order of that entry, requiring a new sort, and a reloading of the tableView again! We can check if we have the sorted column when the data gets set in - tableView:setObjectValue:forTableColumn:row:

- (void)tableView:(NSTableView *)tv setObjectValue:(id)object 
forTableColumn:(NSTableColumn *)tc row:(int)row;
{
        NSArray *workList = [self workList];
        NSString *ident = [tc identifier];
        if (tv == tableView) {
            PieceWork *work = [workList objectAtIndex:row];
            if ([ident isEqual:@"Description"]) {
                [work setWorkDescription:object];
                [self sortIfSortedOn:ident work:work];
           } else if ....
}

Isn't the devil in the details? Because the tableView will want to "select next" after setObjectValue: is called, the wrong row might be selected if the sort changed the currently selected item's row. By calling this method, we'll first end editing on the tableView so any inadvertent select next is foiled. Note the delay of 0.0 seconds which means to schedule the call of the method after the current event loop finishes:

- (void)afterSort:(PieceWork *)work {
    [[self window] makeFirstResponder:[self window]];
    [self selectWork:work];
}
- (void)sortIfSortedOn:(NSString *)ident work:(PieceWork *)work {
    if ([[[self document] sortColumn] isEqualToString:ident])  {
        int oldPosition
        [[self window] makeFirstResponder:[self window]];
        [[self document] sort];
        [self performSelector:@selector(afterSort:) withObject:work afterDelay:0.0];
    } else [self updateTotalsAndReload];
}

Conclusion

Sorting is something users expect tableViews to do now - and with a little effort, all of your tableViews can sort themselves!


Andrew Stone, andrew@stone.com, is Chief Chef at Stone Design, http://www.stone.com, has this to say about Cocoa and Stone Studio with all due respect to Gary Snyder's Turtle Island, "It's objects all the way down" .

 
AAPL
$101.58
Apple Inc.
+0.72
MSFT
$46.52
Microsoft Corpora
-0.24
GOOG
$584.77
Google Inc.
+4.82

MacTech Search:
Community Search:

Software Updates via MacUpdate

Apple Configurator 1.6 - Configure and d...
Apple Configurator makes it easy for anyone to mass configure and deploy iPhone, iPad, and iPod touch in a school, business, or institution. Three simple workflows let you prepare new iOS devices... Read more
SpamSieve 2.9.16 - Robust spam filter fo...
SpamSieve is a robust spam filter for major email clients that uses powerful Bayesian spam filtering. SpamSieve understands what your spam looks like in order to block it all, but also learns what... Read more
OS X Server 3.2.1 - For OS X 10.9.5 Mave...
OS X Server is the next generation of Apple's award winning server software. Designed for OS X and iOS devices, OS X Server makes it easy to share files, schedule meetings, synchronize contacts, host... Read more
Apple Security Update 2014-004 - For OS...
Apple Security Update is recommended for all users and improves the security of Mac OS X. For information on the security content of this update, please visit this website: http://support.apple.com/... Read more
OS X Mavericks 10.9.5 - The latest versi...
Apple OS X Mavericks is the latest release of the world's most advanced desktop operating system. Now free! With more than 200 new features, OS X Mavericks brings Maps and iBooks to the Mac,... Read more
iExplorer 3.5.0.0 - View and transfer al...
iExplorer is an iPhone browser for Mac lets you view the files on your iOS device. By using a drag and drop interface, you can quickly copy files and folders between your Mac and your iPhone or... Read more
BusyCal 2.6 - Powerful calendar app with...
BusyCal is an award-winning desktop calendar that combines personal productivity features for individuals with powerful calendar sharing capabilities for families and workgroups. BusyCal's unique... Read more
Apple iOS 8.0 - The latest version of Ap...
The latest version of iOS can be downloaded through iTunes. Apple iOS 8 comes with big updates to apps you use every day, like Messages and Photos. A whole new way to share content with your family.... Read more
Apple Digital Camera RAW Compatibility 5...
Apple Digital Camera RAW Compatibility update adds RAW image compatibility to Aperture 3 and iPhoto '11. For more information on supported RAW formats, see here.Version 5.07: Adds RAW camera... Read more
Transmit 4.4.7 - Excellent FTP/SFTP clie...
Transmit is an excellent FTP (file transfer protocol), SFTP, S3 (Amazon.com file hosting) and iDisk/WebDAV client that allows you to upload, download, and delete files over the internet. With the... Read more

Latest Forum Discussions

See All

Paste+ | Clipboard Action Widget (Produ...
Paste+ | Clipboard Action Widget 1.0.0 Device: iOS iPhone Category: Productivity Price: $3.99, Version: 1.0.0 (iTunes) Description: Powerful clipboard widget for iOS 8. Reimagine what you can do with your clipboard! Paste+ is a... | Read more »
Agenda+ | Calendar & Reminder Widget...
Agenda+ | Calendar & Reminder Widget 1.0.0 Device: iOS iPhone Category: Productivity Price: $1.99, Version: 1.0.0 (iTunes) Description: Best Calendar and Reminder Widget Ever for iOS 8 | Read more »
Leg·end·ar·y (Games)
Leg·end·ar·y 1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: Simple and yet complex. Leg•end•dar•y is a grid-based puzzle game based on numbers. Discover the adventure of Leg•end•dar•y and... | Read more »
KuaiBoard (formerly QuickBoard) (Utilit...
KuaiBoard (formerly QuickBoard) 1.0 Device: iOS Universal Category: Utilities Price: $1.99, Version: 1.0 (iTunes) Description: KuaiBoard is currently 50% off for launch! Billing info. Signatures. Locations. KuaiBoard allows you to... | Read more »
Treasure Fetch - Adventure Time (Games)
Treasure Fetch - Adventure Time 1.0.1 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0.1 (iTunes) Description: Adventure Time Treasure Fetch is a fresh take on the classic Snake game! STRETCHY JAKE Snake your way... | Read more »
Light in the Dark (Games)
Light in the Dark 1.1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.1.0 (iTunes) Description: Be enlightened by this delightful puzzle game that has never before seen the light of day! "A physics and color-blending... | Read more »
Transmit iOS (Utilities)
Transmit iOS 1.0 Device: iOS Universal Category: Utilities Price: $9.99, Version: 1.0 (iTunes) Description: >> LAUNCH SPECIAL: Transmit iOS is ONLY $10 for a LIMITED TIME. << THE #1 FILE TRANSFER CLIENT FOR THE MAC NOW... | Read more »
Minuum - The Little Keyboard for Big Fin...
Minuum - The Little Keyboard for Big Fingers 1.0 Device: iOS iPhone Category: Utilities Price: $1.99, Version: 1.0 (iTunes) Description: Type faster, see more of your screen, and take control of autocorrect with Minuum: the little... | Read more »
TextExpander 3 + custom keyboard (Utili...
TextExpander 3 + custom keyboard 3.0 Device: iOS Universal Category: Utilities Price: $4.99, Version: 3.0 (iTunes) Description: | Read more »
Swype - Keyboard (Utilities)
Swype - Keyboard 1.0.1411 Device: iOS Universal Category: Utilities Price: $.99, Version: 1.0.1411 (iTunes) Description: Why type when you can Swype? One of the most requested apps for iPhone is finally here. "If Swype itself ever... | Read more »

Price Scanner via MacPrices.net

Toshiba Introduces TransMemory ID High-Speed...
Toshiba’s Digital Products Division (DPD), a division of Toshiba America Information Systems, Inc., today introduced the TransMemory ID USB 3.0 Flash Drive, a simpler storage solution for people who... Read more
New iPads and OS X Yosemite Release Coming Oc...
The DailyDot’s Micah Singleton reports that Apple is planning to hold its next product announcement event on Oct. 21, at which it will unveil the iPad Air 2 and iPad mini 3 and release a final build... Read more
Logitech Bluetooth Multi-Device Cross-Platfor...
Logitech has an enviable track record of making some of the best computer keyboards and mice. At least in my estimation, the best freestanding keyboards I’ve ever used have been Logitech units,... Read more
Roundup of Apple refurbished iPad Airs and iP...
Apple is offering Certified Refurbished iPad Airs for up to $140 off MSRP. Apple’s one-year warranty is included with each model, and shipping is free. Stock tends to come and go with some of these... Read more
Sprint offers 16GB iPad mini for $199.99 with...
Sprint is offering 1st generation 16GB iPad minis for $199.99 with a 2-year service agreement. Standard MSRP for this iPad is $429. Their price is the lowest available for this model. Read more
2.5GHz Mac mini remains on sale for $549, sav...
B&H Photo has the 2.5GHz Mac mini on sale for $549.99 including free shipping. That’s $50 off MSRP, and B&H will also include a free copy of Parallels Desktop software. NY sales tax only. Read more
Apple refurbished iMacs available for up to $...
The Apple Store has Apple Certified Refurbished iMacs available for up to $300 off the cost of new models. Apple’s one-year warranty is standard, and shipping is free. These are the best prices on... Read more
13″ 2.5GHz MacBook Pro offered for $100 off M...
B&H Photo has the 13″ 2.5GHz MacBook Pro on sale for $999.99 including free shipping plus NY sales tax only. Their price is $100 off MSRP. Read more
Free GIMP Professional Grade Graphics App Ver...
The latest 2.8.14 version of the oddly-named GIMP (acronym for: GNU Image Manipulation Program) open source, high-end image editing and creation alternative to Adobe’s Photoshop and refuge from... Read more
Apple Announces Record Pre-orders for iPhone...
Apple has released metrics showing a record number of first day pre-orders of iPhone 6 and iPhone 6 Plus, with over four million sold in the first 24 hours. Demand for the new iPhones exceeds the... Read more

Jobs Board

*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.