2012-08-14 24 views
0

我在NSArray中有NSdate對象。我想從日期列表中獲取最新信息。最新來自NSArray

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]; 

我的回報值應該是明天(最新日期)。

回答

0

您可以使用:

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

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

其實我需要的最大日期沒有最新添加日期到數組 – Codesen 2012-08-14 06:20:58

+0

在t他的情況下,你需要排序數組,然後把最後一個對象 – Alex 2012-08-14 06:43:00

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. 
+0

或'NSArray * sortedDates = [arr sortedArrayUsingSelector:@selector(compare :)];'。 – 2012-08-14 06:38:28

+0

@MartinR:最初我以爲它不適用於NSDate。但它像魅力工作:) – Aravindhan 2012-08-14 06:56:14