1、数组按照指定关键字升序
NSArray *sortedArray = [unSortedArray sortedArrayUsingComparator:^(id obj1,id obj2) { //升序,key表示比较的关键字 if (obj1.key < obj1.key ) { return NSOrderedAscending; } else { return NSOrderedDescending; } }
2、数组按照指定关键字降序
NSArray *sortedArray = [unSortedArray sortedArrayUsingComparator:^(id obj1,id obj2) { //降序,key表示比较的关键字 if (obj1.key < obj1.key ) { return NSOrderedDescending; } else { retur NSOrderedAscending; } }
3、数组顺序全部翻转
NSMutableArray *tempArray = [NSMutableArray arrayWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",nil]; NSArray *resultArray = [[tempArray reverseObjectEnumerator] allObjects];
4、使用NSDescriptor排序
单个关键字排序
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]];