2010-12-04 40 views
11

的一個NSArray我的NSDate對象的一個​​NSArray,我想這樣,今天是在0對它們進行排序,昨日1等排序NSDates

難道是上升或下降,並做我使用的功能,選擇器還是什麼?

回答

37

對於NSArray有不同的排序方法,因爲可能有不同的方法來排序。 NSSortDescriptors是一種通用的方法,就排序中使用哪些鍵,您想要在這些鍵上使用哪些選擇器以及使用的總體順序等方面給予您很多選擇。或者,您可以使用函數或比較器塊你的情況要求,或者如果這對你的特定情況更方便。

要回答你的第一個問題,如果你想今天成爲第一個問題,那麼在昨天之後,是的,那當然是降序。 (假設一個NSArray全NSDates稱爲「dateArray」的):

降序排列,你可以做一些這方面的日期進行排序

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"self" ascending:NO]; 
NSArray *descriptors = [NSArray arrayWithObject: descriptor]; 
[descriptor release]; 

NSArray *reverseOrder = [dateArray sortedArrayUsingDescriptors:descriptors]; 

或者,如果您正在爲iOS 4以上版本或雪豹+你可以這樣做:

NSArray *reverseOrderUsingComparator = [dateArray sortedArrayUsingComparator: 
             ^(id obj1, id obj2) { 
              return [obj2 compare:obj1]; // note reversed comparison here 
             }]; 
-1

試試這個神奇:

升序排序日期排序排列。

即日期變得越來越晚,或者換句話說,日期是未來的日期。

NSArray ascendingDates = [dates sortedArrayUsingSelector:@selector(compare:)]; 

排序陣列以降序日期。(什麼問的問題)

即日期早,晚得早,紅棗去到過去或者換一種說法:今天是在索引0,昨日在指數1

NSArray* descendingDates = [[[dates sortedArrayUsingSelector:@selector(compare:)] reverseObjectEnumerator] allObjects];