OC中的排序
排序:
1、OC中的冒泡排序(数组)
创建可变数组:NSMutableArray *array = [NSMutableArray arrayWithObjects:@"20", @"10",@"40", @"30", nil];
按照升序进行排列
for (int i = 0; i< array.count-1; i++) {
for (int j = 0; j < array.count-1-i; j++){
NSString * str1 = array[j];
NSString * str2 = array[j+1];
//C语言中比较的返回值是>0 <0 =0
//OC中的compare:的返回值是枚举值
if ([str1 compare:str2] ==NSOrderedDescending) {
[array exchangeObjectAtIndex:jwithObjectAtIndex:j+1];
}
}
}
NSLog(@"SortAscend:%@", array);
2、使用OC中的方法进行排序
可变数组类提供的排序方法,没有返回值,修改的是可变数组本身。
数组实现排序是通过提供排序时的比较方法(动态排序)进行。
传给数组的方法:是数组中元素对象的方法
@selector(方法名)方法选择器
OC中传递方法,使用@selector
sortUsingSelector使用场景,数组中存储的是字符串对象,并且默认实现升序排列。
以下实现数组字符串对象的升序排列:
[array sortUsingSelector:@selector(compare:)];
NSLog(@"%@",array);
sortedArrayUsingSelector实现不可变数组的排序,返回值为新数组。
NSArray * a = [arraysortedArrayUsingSelector:@selector(compare:)];
NSLog(@"%@",a);
实现降序需要重新定义降序的方法。
3、数组中存储的对象为非字符串类型对象的排序方法
创建数组对象:
Student * stu1 =[[Student alloc] initWithName:@"zhangsan" age:25];
Student * stu2 =[[Student alloc] initWithName:@"lisi" age:26];
Student * stu3 =[[Student alloc] initWithName:@"wangwu" age:24];
//数组存储3个学生对象
NSMutableArray *array = [NSMutableArray arrayWithObjects:stu1, stu2, stu3, nil];
(1)基本数据类型,如:NSInteger类型
实现按照age进行升序排列
声明和实现元素对象age的升序排列方法
-(NSComparisonResult)compareStudentByAgeAscend:(Student *)otherStu
{
// 前 > 后 返回降序
if (_age > otherStu.age) {
return NSOrderedDescending;
// 前 < 后 返回升序
} else if (_age < otherStu.age){
return NSOrderedAscending;
// 前 = 后 返回0,不变
} else {
return NSOrderedSame;
}
}
数组使用方法:
[arraysortUsingSelector:@selector(compareStudentByAgeAscend:)];
按照age进行降序排列,在和升序的方法类型一致,比较采用相反的方法:
-(NSComparisonResult)compareStudentByAgeDescend:(Student *)otherStu
{
if (_age < otherStu.age) {
return NSOrderedDescending;
} else if (_age > otherStu.age){
return NSOrderedAscending;
} else {
return NSOrderedSame;
}
}
(2)实现按照姓名升序排列
OC中提供的字符串的比较方法为compare:,默认返回值为升序
-(NSComparisonResult)compareStudentByNameAscend:(Student *)otherStu
{
return [_name compare:otherStu.name];
}
按照姓名降序排列的比较方法
将compare:的默认值取反,即得到相反的方法。
-(NSComparisonResult)compareStudentByNameDescend:(Student *)otherStu
{
return -[_name compare:otherStu.name];
}
4、使用block进行排序
使用场景:数组中存储的是非字符串对象,一般需要使用带block的排序方法。
block实现的功能就是定义的比较方法
返回值:两个数组元素对象比较后的结果(枚举值)
参数:进行比较的两个数组元素对象
数组将进行比较的两个对象传入block,我们按照需求实现比较功能,将比较结果返回给数组。
按照年龄升序排列
[arraysortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
Student *s1 =(Student *)obj1;//说明参数指向的类型
Student *s2 =(Student *)obj2;
return s1.age > s2.age;
// return s1.age <s2.age;得到降序的排列
}];
NSLog(@"%@",array);
按照姓名升序排列
[arraysortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
Student *s1 =(Student *)obj1;//说明参数指向的类型
Student *s2 =(Student *)obj2;
return [s1.name compare:s2.name];
//return [s1.name compare:s2.name];得到姓名的降序排列
}];
NSLog(@"%@",array);