zoukankan      html  css  js  c++  java
  • 排序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
    }
  • 相关阅读:
    关于Date相关函数在火狐Firefox和谷歌Chrome下的不同
    一键部署 LNMP 建站环境
    Python 返回值、方法和函数的区别
    Python中万物皆对象?的理解
    Python 实用小工具 练习(2)
    Chrome浏览器F12开发者工具使用教程博客汇总
    觅风易语言[21-24、30]
    觅风易语言[1-10]
    觅风易语言[11-20]
    Python Byte类型(API系列)
  • 原文地址:https://www.cnblogs.com/xiaobaizhu/p/3056547.html
Copyright © 2011-2022 走看看