Sorting an NSArray of NSString

為{幸葍}努か 提交于 2019-11-29 03:03:15

It's pretty simple to write your own comparison method for strings:

@implementation NSString(compare)

-(NSComparisonResult)compareNumberStrings:(NSString *)str {
    NSNumber * me = [NSNumber numberWithInt:[self intValue]];
    NSNumber * you = [NSNumber numberWithInt:[str intValue]];

    return [you compare:me];
}

@end
HyLian

You should use this method:

[arr sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];

in a NSArray or:

[arr sortUsingSelector:@selector(caseInsensitiveCompare:)];

in a "inplace" sorting NSMutableArray

The comparator should return one of this values:

  • NSOrderedAscending
  • NSOrderedDescending
  • NSOrderedSame
Eric

If the array's elements are just NSStrings with digits and no letters (i.e. "8", "25", "3", etc.), here's a clean and short way that actually works:

NSArray *sortedArray = [unorderedArray sortedArrayUsingComparator:^(id a, id b) {
    return [a compare:b options:NSNumericSearch];
}];

Done! No need to write a whole method that returns NSComparisonResult, or eight lines of NSSortDescriptor...

IMHO, easiest way to sort such array is

[arr sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"self.intValue" ascending:YES]]]

If your array contains float values, just change key to self.floatValue or self.doubleValue

The easiest way would be to make a comparator method like this one

NSArray *sortedStrings = [stringsArray sortedArrayUsingComparator:^NSComparisonResult(NSString *firstString, NSString *secondString) {
    return [[firstString lowercaseString] compare:[secondString lowercaseString]];
}];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!