如果数组里面的每一个元素都是一个个model,例如
DepartsDate.h文件
[plain] view
plaincopy
plaincopy
- #import <Foundation/Foundation.h>
- @interface DepartsDate : NSObject
- @property (nonatomic, retain) NSDate *date;
- @property (nonatomic, assign) int price;
- @end
DepartsDate.m文件
[plain] view
plaincopy
plaincopy
- #import "DepartsDate.h"
- @implementation DepartsDate
- @synthesize date, price;
- - (void)dealloc
- {
- [date release];
- [super dealloc];
- }
- @end
那么对这个数组排序就可以这样
[plain] view
plaincopy
plaincopy
- NSMutableArray *array = [NSMutableArray array];
- ......
- NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"date" ascending:YES];[array sortUsingDescriptors:[NSArray arrayWithObject:sort]];
这是按照时间升序排列。如果需要降序,那么将YES改为NO。
使用NSSortDescriptor可以很方便的进行多条件排序,例如:同样是上面的假设,首先按照价格升序排列;当价格相同时,按照日期降序排列。
[plain] view
plaincopy
plaincopy
- NSMutableArray *array = [NSMutableArray array];
- ......
- NSSortDescriptor *sort1 = [NSSortDescriptor sortDescriptorWithKey:@"price" ascending:YES];
- NSSortDescriptor *sort2 = [NSSortDescriptor sortDescriptorWithKey:@"date" ascending:NO];
- [array sortUsingDescriptors:[NSArray arrayWithObjects:sort1, sort2, nil]];