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