NSSortDescriptor(数组排序)

时间:2023-03-09 03:09:19
NSSortDescriptor(数组排序)

如果数组里面的每一个元素都是一个个model,例如

DepartsDate.h文件

[plain] view
plain
copy
  1. #import <Foundation/Foundation.h>
  2. @interface DepartsDate : NSObject
  3. @property (nonatomic, retain) NSDate *date;
  4. @property (nonatomic, assign) int    price;
  5. @end

DepartsDate.m文件

[plain] view
plain
copy
  1. #import "DepartsDate.h"
  2. @implementation DepartsDate
  3. @synthesize date, price;
  4. - (void)dealloc
  5. {
  6. [date release];
  7. [super dealloc];
  8. }
  9. @end

那么对这个数组排序就可以这样

[plain] view
plain
copy
  1. NSMutableArray *array = [NSMutableArray array];
  2. ......
  3. NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"date" ascending:YES];[array sortUsingDescriptors:[NSArray arrayWithObject:sort]];

这是按照时间升序排列。如果需要降序,那么将YES改为NO。

使用NSSortDescriptor可以很方便的进行多条件排序,例如:同样是上面的假设,首先按照价格升序排列;当价格相同时,按照日期降序排列。

[plain] view
plain
copy
  1. NSMutableArray *array = [NSMutableArray array];
  2. ......
  3. NSSortDescriptor *sort1 = [NSSortDescriptor sortDescriptorWithKey:@"price" ascending:YES];
  4. NSSortDescriptor *sort2 = [NSSortDescriptor sortDescriptorWithKey:@"date" ascending:NO];
  5. [array sortUsingDescriptors:[NSArray arrayWithObjects:sort1, sort2, nil]];