OC 集合排序

数组排序:

//Student类里面只是声明公共NSString *name,NSInteger age变量

//Student.m文件里面重写-(NSString *)description函数

//写  return [NSString stringWithFormat:@"%@,%ld",name,age];

//这条代码是为了后面输出的时候看name和age

Student* stu1=[Student new];

stu1->name=@"ggg";

stu1->age=33;

Student* stu2=[Student new];

stu2->name=@"dd";

stu2->age=22;

//排序器,第一个参数指明排序的依据,第二个指明排序的升降序

NSSortDescriptor* des1=[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];

NSSortDescriptor* des2=[NSSortDescriptor sortDescriptorWithKey:@"age" ascending:NO];

//不可变数组NSArray

NSArray *arr1=@[stu1,stu2];

//由于NSArray是不可变数组,所以要创建一个新的数组来接收返回值

NSArray *arr2=[arr1 sortedArrayUsingDescriptors:@[des1,des2]];//arr2已经排好序

//可变数组:NSMutableArray

NSMutableArray* marr1=[[NSMutableArray alloc]initWithObjects:stu1,stu2,nil];

//可变数组不用创建新的数组

[marr1 sortUsingDescriptors:@[des1,des2]];

//输出

NSLog(@"%@",arr1);

NSLog(@"%@",arr2);

NSLog(@"%@",marr1);

自定义方法排序:

在Student.h文件添加:-(NSComparisonResult)compare:(Student* )otherStu;

在Student.m文件实现:

-(NSComparisonResult)compare:(Student *)otherStu

{

    //假设以名字来排序

    NSComparisonResult rst=[name compare:otherStu->name];//原有的name跟传进来的name 比较

    NSLog(@"asdfasf");

    return rst;

}

在main文件实现

NSMutableArray *marr3=maar2;

 [marr3 sortUsingSelector:@selector(compare:)];

NSLog(@"marr3:%@",marr3);

代码块排序:

首先复习下代码块的内容:

//代码块跟C语言里面的函数差不多

//1.声明代码块:

//三要素:返回值、代码块名、参数列表

//没有参数也要写一个()

void (^hello)();//返回值是void,代码块名是hello,没有参数

hello=^{

  NSLog(@"hello");

};//后面记得分号

int (^sum)(int ,int )=^(int a,int b){

  return a+b;

};//有参数的代码块

//调用代码块:

 NSLog(@"%d", sum(3,5));//输出8

//下面是利用代码块的排序:

//随便输入一些字母

NSMutableArray* marr=[NSMutableArray arrayWithObjects:@"asdasd",@"sadasfg",@"ryerqwr",nil];

//用系统提供的代码块:

[marr sortUsingComparator:^NSComparisonResult(id obj1,id obj2)

{

NSComparisonResult result=[obj1 compare:obj2];//字符串的比较

return result;

}];

NSLog(@"marr:%@",marr);//这样就排序好了,是不是很简单?

//但这种方发不能排序int类型,下面介绍自定义代码块排序

NSMutableArray* marr2=[NSMutableArray arrayWithObjects:@234,@43534,@5435,nil];

//自定义一个比较的代码块:

//分析参数类型,NSMutableArray里面是对象,所以参数是封装的NSInteger类型,所以参数是NSNumber。

NSComparisonResult (^numComper)(NSNumber*,NSNumber*)=^(NSNumber*num1,NSNumber*num2)

{   

       return (NSComparisonResult)(num1.intValue - num2.intValue);//比较的时候需要解除封装,返回值不同所以需要强转  

};

[marr2 sortUsingComparator:numComper];

NSLog(@"marr2=%@",marr2);

原文地址:https://www.cnblogs.com/mojiewei/p/4786728.html