Skip to content

Instantly share code, notes, and snippets.

@jordanekay
Last active December 18, 2015 01:19
Show Gist options
  • Save jordanekay/5703459 to your computer and use it in GitHub Desktop.
Save jordanekay/5703459 to your computer and use it in GitHub Desktop.
Naturally sorting a list of titles in Cocoa
#import <Foundation/Foundation.h>
@implementation NSString (JEKNormalization)
- (NSString *)jek_normalizedString
{
__block NSString *normalizedString = self;
[self enumerateLinguisticTagsInRange:NSMakeRange(0, self.length) scheme:NSLinguisticTagSchemeLexicalClass options:~NSLinguisticTaggerOmitWords orthography:nil usingBlock:^(NSString *tag, NSRange tokenRange, NSRange sentenceRange, BOOL *stop) {
if (tag == NSLinguisticTagDeterminer && tokenRange.location == 0) {
normalizedString = [self substringFromIndex:tokenRange.length + 1];
*stop = YES;
}
}];
return normalizedString;
}
@end
@implementation NSArray (JEKNaturalSort)
- (NSArray *)jek_naturallySortedArray
{
return [self sortedArrayUsingComparator:^(NSString *x, NSString *y) {
return [[x jek_normalizedString] caseInsensitiveCompare:[y jek_normalizedString]];
}];
}
@end
int main(int argc, const char *argv[])
{
@autoreleasepool {
NSArray *titles = @[@"A Christmas Carol",
@"Great Expectations",
@"Oliver Twist",
@"A Tale of Two Cities",
@"David Copperfield",
@"Hard Times",
@"Bleak House",
@"The Life and Adventures of Nicholas Nickleby",
@"Little Dorrit"];
NSLog(@"%@", [titles jek_naturallySortedArray]);
/*(
"Bleak House",
"A Christmas Carol",
"David Copperfield",
"Great Expectations",
"Hard Times",
"The Life and Adventures of Nicholas Nickleby",
"Little Dorrit",
"Oliver Twist",
"A Tale of Two Cities"
)*/
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment