来自NSArray的最新消息

时间:2012-08-14 06:09:09

标签: ios nsarray nsdate

我在NSArray中有NSdate对象。我希望从日期数组中获得最新信息。

NSDate *tomorrow = [NSDate dateWithTimeInterval:(24*60*60) sinceDate:[NSDate date]];

    NSDate *today = [NSDate date];

    NSDate *yesterday = [NSDate dateWithTimeInterval:-(24*60*60) sinceDate:[NSDate date]];


    NSMutableArray* arr = [[NSMutableArray alloc] initWithObjects:today,yesterday,tomorrow,today,yesterday,tomorrow, nil];

我的返回值应该是明天(最晚的日期)。

2 个答案:

答案 0 :(得分:0)

您可以使用:

[arr lastObject]; //Returns the object in the array with the highest index value.

[arr objectAtIndex:[arr count]-1];

答案 1 :(得分:0)

您可以使用sortedArrayUsingComparatorcompare进行此操作来自NSArray&分别为NSDate类

NSArray *sortedDates = [arr sortedArrayUsingComparator: 
                                                     ^(id obj1, id obj2) {
                                                          return [obj1 compare:obj2];
                                                     }];
NSLog(@"%@",[sortedDates lastObject]); // SortedDates Contains dates in ascending Order (last object of the array returns the latest date.