2012-11-29 73 views
0

可能重複:
Comparing version numbers
How to use compare on a version number where theres less parts in one number in Objective-C?Objective-C的版本比較

我試圖排序基於一個名爲referenceID性質基本上類似於一個版本的自定義對象的NSMutableArray數。

看來,治療referenceIDNSNumber和使用compareTo:排序幾乎得到它的權利,但如果它打破的情況下,如:

Result:   Should Be: 
1.1.1    1.1.1 
1.1.10   1.1.2 
1.1.2    ... 
...    1.1.9 
1.1.9    1.1.10 

(Where ... is 1.1.2 through 1.1.9) 

是否有任何內置的,這將解決這正常功能呢?或者我應該開始編寫排序算法?

+1

也會檢出【使用方法比較上一個版本號,其中那裏有少在Objective-C中的一個數字中的部分?](http://stackoverflow.com/questions/12308659/how-to-use-compare-on-a-version-number-where-theres-less-parts-in-one -number-in) –

+0

啊,謝謝。我的溢出搜索技能需要一些工作... – kz3

回答

2

如果您的參考編號是一個字符串,你可以使用localizedStandardCompare:,這串根據其數值進行比較的數字。

例(含sortedArrayUsingComparator,因爲那是在他的評論中所使用的OP):

NSArray *versions = @[@"2.1.1.1", @"2.10.1", @"2.2.1"]; 
NSArray *sorted = [versions sortedArrayUsingComparator:^NSComparisonResult(NSString *s1, NSString *s2) { 
    return [s1 localizedStandardCompare:s2]; 
}]; 
NSLog(@"%@", sorted); 

輸出:

2012-11-29 23:51:28.962 test27[1962:303] (
    "2.1.1.1", 
    "2.2.1", 
    "2.10.1" 
) 
+0

他有版本號雖然..點分離版本的不同長度。函數做到了嗎? –

+0

@ Daij-Djan:是的,它可以處理不同長度的數字。 –

+0

也許我在這裏做錯了什麼,但我仍然得到了與上面相同的結果: [標準sortedArrayUsingComparator:^ NSComparisonResult(Standard * s1,Standard * s2) { return [[NSString stringWithFormat: @「%@」,s1.referenceID] localizedStandardCompare:[NSString stringWithFormat:@「%@」,s2.referenceID]]; – kz3

0

與塊排序它


@autoreleasepool { 
    //in this example, array of NSStrings 
    id array = @[@"1.1.1",@"2.2",@"1.0",@"1.1.0.1",@"1.1.2.0", @"1.0.3", @"2.1.1.1", @"2.1.1", @"2.1.10"]; 

    //block 
    id sorted = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) { 
     NSArray *comps1 = [obj1 componentsSeparatedByString:@"."]; 
     NSArray *comps2 = [obj2 componentsSeparatedByString:@"."]; 

     //get ints from comps 
     int res1 = 0; 
     for (int i=0; i<comps1.count; i++) { 
      res1 += [comps1[i] intValue] * (4 - i); 
     } 
     int res2 = 0; 
     for (int i=0; i<comps2.count; i++) { 
      res2 += [comps2[i] intValue] * (4 - i); 
     } 

     return res1<res2 ? NSOrderedAscending : res1>res2 ? NSOrderedSame : NSOrderedDescending; 
    }]; 

    NSLog(@"%@", sorted); 
}