排序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
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM