1

我需要使用项目字典的“日期”键对我的数组进行排序。最后,我需要具有某种结构的数组作为我的 mData 数组,但需要对日期进行排序。

mData---------->( { items = ( { Accuracy = 5; Address = "Australia, Sydney CBD, Bridge Street"; Course = "0.00"; Date = "2013-08-20 06:50:28 +0000"; Speed = 3; alt = 0; lat = "-33.8634"; lon = "151.211"; }, { Accuracy = 65; Address = "Armenia, Yerevan, \U053f\U0561\U056c\U0565\U0576\U0581\U056b \U0583\U0578\U0572\U0578\U0581"; Course = "0.00"; Date = "2013-08-20 06:41:02 +0000"; Speed = 3; alt = 1116; lat = "40.20016076"; lon = "44.49在此处输入代码130268"; } ); name = Name; startTime = "10:40"; } ) 我的数组看起来像 2。NSDictionary * mFirst = [NSDictionary dictionaryWithObjectsAndKeys:[NSDate distantFuture], @"Date", nil]; NSDictionary * mSecond = [NSDictionary dictionaryWithObjectsAndKeys:[NSDate distantPast], @"Date", nil]; NSArray *mArr = [[NSArray alloc]initWithObjects:mFirst,mSecond, nil]; NSDictionary * myDict = [NSDictionary dictionaryWithObject:mArr forKey:@"items"]; NSArray * mSortedArray = [[ NSArray alloc]initWithObjects:myDict, nil]; NSLog(@"%@", mSortedArray);

4

1 回答 1

0

用这个:

    NSSortDescriptor *dateDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"Date" ascending:YES] autorelease];
    NSArray *sortDescriptors = [NSArray arrayWithObject:dateDescriptor];
    NSArray *sortedArray = [myArray sortedArrayUsingDescriptors:sortDescriptors];

更新: 我用过这个:

NSArray *myArray = [[NSArray alloc] initWithObjects:[NSDictionary dictionaryWithObjectsAndKeys:[NSDate distantFuture], @"Date", nil],
        [NSDictionary dictionaryWithObjectsAndKeys:[NSDate distantPast], @"Date", nil], nil];
    NSLog(@"%@", myArray);
    NSSortDescriptor *dateDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Date" ascending:YES];
    NSArray *sortDescriptors = [NSArray arrayWithObject:dateDescriptor];
    NSArray *sortedArray = [myArray sortedArrayUsingDescriptors:sortDescriptors];
    NSLog(@"%@", sortedArray);

并得到日志:

排序前: ( { Date = "4001-01-01 00:00:00 +0000"; }, { Date = "0001-12-30 00:00:00 +0000"; } ) 排序后: ( { Date =“0001-12-30 00:00:00 +0000”;},{日期 =“4001-01-01 00:00:00 +0000”;})

请在使用上述代码时检查。

于 2013-08-20T07:07:51.300 回答