ios排序NSArray(数字.字符串)

 

 NSArray *originalArray = @[@"1",@"21",@"12",@"11",@"0"];

    //block比较方法,数组中可以是NSInteger,NSString(需要转换)

        NSComparator finderSort = ^(id string1,id string2){

 

            if ([string1 integerValue] > [string2 integerValue]) {

                return (NSComparisonResult)NSOrderedDescending;

            }else if ([string1 integerValue] < [string2 integerValue]){

                return (NSComparisonResult)NSOrderedAscending;

            }

            else

            return (NSComparisonResult)NSOrderedSame;

        };

    

    //数组排序:

    NSArray *resultArray = [originalArray sortedArrayUsingComparator:finderSort];

    NSLog(@"第一种排序结果:%@",resultArray);

 

如果NSArray里面的不是数字,不能转换成NSInteger,就要用字符串的比较方法了

 

    NSArray *charArray = @[@"string 1",@"String 21",@"string 12",@"String 11",@"String 02"];

    NSStringCompareOptions comparisonOptions = NSCaseInsensitiveSearch|NSNumericSearch|

    NSWidthInsensitiveSearch|NSForcedOrderingSearch;

    NSComparator sort = ^(NSString *obj1,NSString *obj2){

        NSRange range = NSMakeRange(0,obj1.length);

        return [obj1 compare:obj2 options:comparisonOptions range:range];

    };

    NSArray *resultArray2 = [charArray sortedArrayUsingComparator:sort];

    NSLog(@"字符串数组排序结果%@",resultArray2);

 

对于NSStringCompareOptions,大家可以看看系统的说明:

enum{

    NSCaseInsensitiveSearch = 1,//不区分大小写比较

    NSLiteralSearch = 2,//区分大小写比较

    NSBackwardsSearch = 4,//从字符串末尾开始搜索

    NSAnchoredSearch = 8,//搜索限制范围的字符串

    NSNumbericSearch = 64//按照字符串里的数字为依据,算出顺序。例如 Foo2.txt < Foo7.txt < Foo25.txt

//以下定义高于 mac os 10.5 或者高于 iphone 2.0 可用

    ,

    NSDiacriticInsensitiveSearch = 128,//忽略 "-" 符号的比较

    NSWidthInsensitiveSearch = 256,//忽略字符串的长度,比较出结果

    NSForcedOrderingSearch = 512//忽略不区分大小写比较的选项,并强制返回 NSOrderedAscending 或者 NSOrderedDescending

//以下定义高于 iphone 3.2 可用

    ,

    NSRegularExpressionSearch = 1024//只能应用于 rangeOfString:..., stringByReplacingOccurrencesOfString:... replaceOccurrencesOfString:... 方法。使用通用兼容的比较方法,如果设置此项,可以去掉 NSCaseInsensitiveSearch NSAnchoredSearch

}

posted @ 2018-01-03 15:33  给me一首歌的时间  阅读(110)  评论(0编辑  收藏  举报