根据字段排序之前一直使用sortedArrayUsingComparator方法,
NSArray *sortedArray = [unSortedArray sortedArrayUsingComparator:^(idobj1,id obj2){
if(obj1.key < obj1.key ){
return NSOrderedAscending;
} else {
return NSOrderedDescending;
}
}
某一天,发现新世界的大门,接触到[NSSortDescriptor sortDescriptorWithKey:@"" ascending:YES]方法,感觉比上述方便更加便捷,所以记录一下。
单个关键字排序:
NSMutableArray *array = [NSMutableArray array];
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"key" ascending:YES];
[array sortUsingDescriptors:[NSArray arrayWithObject:sort]];
多个关键字排序:
按照添加时的字段顺序进行排序
NSMutableArray *array = [NSMutableArray array];
NSSortDescriptor *sort1 = [NSSortDescriptor sortDescriptorWithKey:@"key1" ascending:YES];
NSSortDescriptor *sort2 = [NSSortDescriptor sortDescriptorWithKey:@"key2" ascending:NO];
......
[array sortUsingDescriptors:[NSArray arrayWithObjects:sort1, sort2, nil]];