1、NSArray *originalArray = @[@"1",@"21",@"12",@"11",@"0"];//block比较方法,数组中可以是NSInteger,NSString(需要转换)NSComparator finderSort = ^(idstring1,idstring2){if([string1 integerValue] >[string2 integerValue]) {return(NSComparisonResult)NSOrderedDescending;
}elseif([string1 integerValue] <[string2 integerValue]){return(NSComparisonResult)NSOrderedAscending;
}elsereturn(NSComparisonResult)NSOrderedSame;
};//数组排序:NSArray *resultArray =[originalArray sortedArrayUsingComparator:finderSort];
NSLog(@"第一种排序结果:%@",resultArray);
2、如果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}