2

フィールド「date」でNSMutableArrayを並べ替えていますが、時間が考慮されていません。日付が同じ場合でも、時刻はランダムに並べ替えられます。私は何が間違っているのですか?フィールド「date」のタイプはNSDateです。

 NSSortDescriptor *dateDescriptor =
[[NSSortDescriptor alloc] initWithKey:@"date" ascending:YES];
NSArray *descriptors = [NSArray arrayWithObjects:dateDescriptor, nil];

[self.player1ScoreT sortedArrayUsingDescriptors:descriptors];

私の出力は次のとおりです:
2012-11-25 11:01:00 +0000
2012-11-25 11:00:56 +0000
2012-11-25 11:00:54 +0000
2012-11-25 11:01:03 +0000

変.....

4

2 に答える 2

4

並べ替えに使用しているロジックは正しいです。試したところ、問題なく動作します。

のせいで[self.player1ScoreT sortedArrayUsingDescriptors:descriptors];、保持されている配列は変更されself.player1ScoreT、新しい配列が生成されると思います。これは、元の配列を変更しないセレクターを使用しているためです(NSArrayそれ自体は設計上変更できず、変更NSMutableArray可能です)。

そのため、これを使用する必要があります。

self.player1ScoreT = [self.player1ScoreT sortedArrayUsingDescriptors:descriptors];

これにより、内のself.player1ScoreT配列が、によって生成された新しい並べ替えられた配列に再割り当てされsortedArrayUsingDescriptors:、古い並べ替えられていない配列は破棄されます。

于 2012-11-25T11:36:25.103 に答える
0

WDUKが言うように、sortedArrayの割り当てがありません。

id newArray = [oldArray sortedArrayUsing...

私もそれを試しました、そしてそれは時間を含む日付を大丈夫に分類します

私が試したコード:

int main(int argc, char *argv[]) {
@autoreleasepool {
    id player1ScoreT = @[@{@"date":[NSDate dateWithTimeIntervalSinceNow:-100]},
                         @{@"date":[NSDate dateWithTimeIntervalSinceNow:-1000]},
                         @{@"date":[NSDate dateWithTimeIntervalSinceReferenceDate:+1000]},
                         @{@"date":[NSDate dateWithTimeIntervalSinceReferenceDate:-50]},
                         @{@"date":[NSDate dateWithTimeIntervalSinceNow:+50]},
                         @{@"date":[NSDate dateWithTimeIntervalSinceNow:+0]}];
    NSLog(@"%@", [player1ScoreT valueForKeyPath:@"date"]);
    player1ScoreT = [player1ScoreT sortedArrayUsingDescriptors:@[[[NSSortDescriptor alloc] initWithKey:@"date" ascending:YES]]];
    NSLog(@"%@", [player1ScoreT valueForKeyPath:@"date"]);
}
}
于 2012-11-25T11:30:59.973 に答える