排序NSDrray的NSArray,其中包含字典数组

时间:2013-08-20 07:04:33

标签: ios nspredicate

我需要用项目字典的“Date”键对我的数组进行排序。最后我需要一些结构作为我的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);

1 个答案:

答案 0 :(得分: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);

得到了日志:

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

使用上述代码时请检查。