sorting an NSArray of NSDates

后端 未结 2 1584
星月不相逢
星月不相逢 2021-01-02 04:17

I have an NSArray of NSDate objects and I want to sort them so that today is at 0, yesterday at 1 etc.

Is it ascending or descending, and do i use a function, select

2条回答
  •  走了就别回头了
    2021-01-02 05:05

    Try this magic:

    Sort array of dates in ascending order.

    i.e. dates getting later and later, or to put it another way, dates going into the future.

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

    Sort array of dates in descending order. (what the question asked)

    i.e. dates getting earlier and earlier, dates going into the past or to put it another way: today is at index 0, yesterday at index 1.

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

提交回复
热议问题