0

重複の可能性:
バージョン番号
の比較 Objective-C で 1 つの番号のパーツが少ないバージョン番号で比較を使用する方法は?

基本的にバージョン番号に似ているNSMutableArrayと呼ばれるプロパティに基づいて、カスタム オブジェクトを並べ替えようとしています。referenceID

referenceIDとして扱い、NSNumberを使用して並べ替えると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)

これを適切にソートする組み込み関数はありますか? それとも、ソート アルゴリズムの作成を開始する必要がありますか?

4

2 に答える 2

2

参照 ID が文字列の場合localizedStandardCompare:、数値に従って文字列内の数値を比較する を使用できます。

例(sortedArrayUsingComparatorOPがコメントで使用しているため):

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"
)
于 2012-11-29T22:29:06.813 に答える
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);
}
于 2012-11-29T22:16:57.017 に答える