Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2603810
  • 博文数量: 877
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 5920
  • 用 户 组: 普通用户
  • 注册时间: 2013-12-05 12:25
个人简介

技术的乐趣在于分享,欢迎多多交流,多多沟通。

文章分类

全部博文(877)

文章存档

2021年(2)

2016年(20)

2015年(471)

2014年(358)

2013年(26)

分类: iOS平台

2015-11-16 17:35:43

http://www.cnblogs.com/xiaobaizhu/archive/2013/05/03/3056547.html
排序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 }
阅读(923) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~