数组排序:对象数组中根据对象的某个字段排序

时间:2020-12-27 15:00:37
  1. 开发中,经常碰到数组的排序问题,当然原始的冒泡、选择排序,还是比较好用的。
  2. 我们常常需要后台排好序再返回,当然也有需要前端排序的。我觉得数组的排序,根据对象数组的某个字段排序,是非常常见的。现在来说说:

  • sortedArrayUsingSelector
 - (void)sortArray1
{
NSArray *tempArray = [NSArray arrayWithObjects:@"abc",@"123",@"bac",@"345",@"Abc", nil];
//compare:使用的是字符串自带的方法
NSArray *sortArray = [tempArray sortedArrayUsingSelector:@selector(compare:)];
NSLog(@"%@",sortArray);
}

这种是最简单的排序。直接对数组进行排序。
- 我们看自定义compare的

//Car类 .h文件
@interface Car : NSObject
@property(nonatomic,copy)NSString *carId;
@property(nonatomic,assign)int carBuyTime;

+ (instancetype)CarWithCarId:(NSString *)carId andCarBuyTime:(int)carBuyTime;
- (NSComparisonResult)compareCar:(Car *)car;
@end
//.m 文件
#import "Car.h"

@implementation Car
+ (instancetype)CarWithCarId:(NSString *)carId andCarBuyTime:(int)carBuyTime
{
Car *car = [[Car alloc]init];
car.carId = carId;
car.carBuyTime = carBuyTime;
return car;
}

- (NSComparisonResult)compareCar:(Car *)car
{
//先按照购买时间排序
NSComparisonResult result = [[NSNumber numberWithInt:car.carBuyTime]compare:[NSNumber numberWithInt:self.carBuyTime]];
if (result == NSOrderedSame) {
result = [car.carId compare:car.carId];
}
return result;
}
@end

控制器调用:

- (void)sortArray2
{
Car *car2 = [Car CarWithCarId:@"87323" andCarBuyTime:1988];
Car *car3 = [Car CarWithCarId:@"87323" andCarBuyTime:1962];
Car *car4 = [Car CarWithCarId:@"66666" andCarBuyTime:1970];
Car *car1 = [Car CarWithCarId:@"32311" andCarBuyTime:1970];
NSArray *array = [NSArray arrayWithObjects:car1,car2,car3,car4, nil];
NSArray *sortedArray = [array sortedArrayUsingSelector:@selector(compareCar:)];
NSLog(@"%@",sortedArray);
}

输出:
数组排序:对象数组中根据对象的某个字段排序


  • sortedArrayUsingComparator
- (void)sortArray3
{
Car *car2 = [Car CarWithCarId:@"87323" andCarBuyTime:1988];
Car *car3 = [Car CarWithCarId:@"87323" andCarBuyTime:1962];
Car *car4 = [Car CarWithCarId:@"66666" andCarBuyTime:1970];
Car *car1 = [Car CarWithCarId:@"32311" andCarBuyTime:1970];
NSArray *array = [NSArray arrayWithObjects:car1,car2,car3,car4, nil];

array = [array sortedArrayUsingComparator:^NSComparisonResult(Car * obj1, Car * obj2) {
NSComparisonResult result = [[NSNumber numberWithInt:obj1.carBuyTime]compare:[NSNumber numberWithInt:obj2.carBuyTime]];
if (result == NSOrderedSame) {
result = [obj1.carId compare:obj2.carId];
}
return result;
}];

}

数组排序:对象数组中根据对象的某个字段排序