Sort using a custom comparator: Difference between revisions
Content deleted Content added
→{{header|Objective-C}}: using sort descriptors |
|||
Line 508:
int l = esign((int)([self length] - [obj length]));
switch(l) {
case(
return NSOrderedAscending; // reverse the ordering
case(
return NSOrderedDescending;
case(
return [self
}
return NSOrderedSame; // should never run this...
Line 540:
[pool release];
return EXIT_SUCCESS;
}</lang>
This example can also be written using sort descriptors:
{{works with|GNUstep}}
{{works with|Cocoa}}
<lang objc>#import <Foundation/Foundation.h>
int main()
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSArray *strings = [@"Here are some sample strings to be sorted" componentsSeparatedByString:@" "];
NSSortDescriptor *sd1 = [[NSSortDescriptor alloc] initWithKey:@"length" ascending:NO];
NSSortDescriptor *sd2 = [[NSSortDescriptor alloc] initWithKey:@"lowercaseString" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sd1, sd2, nil];
[sd1 release];
[sd2 release];
NSArray *sorted = [strings sortedArrayUsingDescriptors:sortDescriptors];
NSLog(@"%@", sorted);
[pool release];
return 0;
}</lang>
|