Mailing Lists: Apple Mailing Lists

Image of Mac OS face in stamp
 
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Sorting NSTableView



malcom skrev:
Damn this is a wonderful thread!
Ok I've found the solution. This is the method used when user click on
outlineview header:
<snip>

I think your solution is somewhat complex. As I have done it I only implement the delegate method:
outlineView:sortDescriptorsDidChange:


It is called every time the user changes any sort ordering. The code for this method is quite short:
- (void)outlineView:(NSOutlineView *)outlineView sortDescriptorsDidChange:(NSArray *)oldDescriptors
{
NSArray *selectedItems = [outlineView selectedRowItems];
NSArray *newDescriptors = [outlineView sortDescriptors];
[[[_messages nodeForName:@"ROWDATA"] objectValue] sortUsingDescriptors:newDescriptors];
[outlineView reloadData];
[outlineView selectRowItems:selectedItems byExtendingSelection:NO];
}


And if I skip all the fluff that is specific to my application (Retaining selections and fetching data from a larger XML tree) you get:
- (void)outlineView:(NSOutlineView *)outlineView sortDescriptorsDidChange:(NSArray *)oldDescriptors
{
NSArray *newDescriptors = [outlineView sortDescriptors];
[_myMutableArrayWithData sortUsingDescriptors:newDescriptors];
[outlineView reloadData];
}


The trick here is to _not write any sort method yourself_, but trust the sortUsingDescriptors: method of NSMutableArray. In order for this to work the instances of the mutable array must be key value encodable (Some one please correct me on this term?) for the values you want to sort on. You have date and author, so simply providing:
- (NSDate *)date;
- (NSString *)author;
I your class would do the trick (And set "date" and "author" as Sort keys in IB).


As you can see you end up with 3 lines of code, automatic ascending/descending, multiple sort criteria, automagically saving sorts to user defaults, and all for free :).

// Fredrik Olsson
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list      (email@hidden)
Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/email@hidden

This email sent to email@hidden
References: 
 >Sorting NSTableView (From: malcom <email@hidden>)
 >Re: Sorting NSTableView (From: malcom <email@hidden>)
 >Re: Re: Sorting NSTableView (From: malcom <email@hidden>)



Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2007 Apple Inc. All rights reserved.