Sorting NSArray which many contain number

对着背影说爱祢 提交于 2019-11-28 20:43:10

You can use NSArray's -sortedArrayUsingComparator: method to get a sorted array using a custom block. I find this more convenient than -sortedArrayUsingSelector:, because you can declare the comparator inline, like so:

NSArray *unsortedArray = [NSArray arrayWithObjects:@"Hello", @"4", @"Hi", @"5", @"2", @"10", @"1", nil];
NSArray *sortedArray = [unsortedArray sortedArrayUsingComparator:^(NSString *str1, NSString *str2) {
    return [str1 compare:str2 options:NSNumericSearch];
}];

This will return an array that looks like so:

(
    1,
    2,
    4,
    5,
    10,
    Hello,
    Hi
)

In general, it's pretty nice to use blocks because they eliminate the need to create random selectors that run amuk in your code.

try using -[NSString compare:options:] with NSNumericSearch. To use that with -sortedArrayUsingSelector: you have to wrap the compare call into a separate category method on NSString:

- (NSComparisonResult)numericCompare:(NSString *)aString {
    return [self compare:aString options:NSNumericSearch];
}
SGRKDL

For sorting Descending

NSArray *sortedArray = [arrayToSort sortedArrayUsingComparator:^(NSString *str1, NSString *str2) {
    return [str1 compare:str2 options:NSNumericSearch];
}];
sortedArray = [[sortedArray reverseObjectEnumerator] allObjects];`

And for asending

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