【黑马程序员】NSArray排序实践应用,高级方法与非高级方法的运用

来源:互联网 发布:linux 线程挂起 编辑:程序博客网 时间:2024/06/07 00:14

---------- IOS培训java培训、期待与您交流! ----------

   oc当中,使用foundation 当中的框架中的 NSArray 或NSMutableArray 来对对象内容进行排序。NSMutableArray 是可变数组,是NSArray的子类,继承NSArray的所有方法。


下面重点介绍对数组的排序:
一 简单排序


返回一个数组,该数组是旧数组的元素经过选择器排序后的新数组。
使用如下:
数组排序
NSArray *array=[NSArray arrayWithObjects:@“1”,@“3”,@“2”];
//返回一个排序好的数组,原来数组元素顺序不变
NSArray *array2=[array sortedArrayUsingSelector:@selector(compare:)];


-(NSComparisonResult)compareStudent:(student *)stu{
//先按照姓排序
NSCoßparisonResult result = [self.lastname compare:stu.lastname];//、、
//如果有相同的姓,就比较名字
if(result == NSOrederedSame){
result = [ self.firstname compare : stu.firstnam];
}
return result;
}
-(NSString *)description{
[NSString stringWithFormat:@“[%@ %@]”,self.lastname ,self.firstname];


NSArray *array = [NSArray arrayWithObjects:stu1,stu2,stu3,stu4,nil];
NSArray *array2=[array sortedArrayUSingSelector:@selector(compareStudents:)];


二 利用block排序



利用block排序
NSArray *array2=[array sortedArrayUsingComparator:
^NSComparisonResult(Student *obj1, Student *obj2){
先按照姓排序
NSComparisonResult result = [obj1.lastname compare:obj2.lastname];
如果有相同的姓,就比较名字
if(result == NSOrederedSame){
result = [ obj1.firstname compare : obj2.firstnam];
}
return result;
}];
NSLog(@“array2”,array2);

三 高级排序


高级排序

//1.先按照书名进行排序

NSSortDescriptor *bookNameDesc = [NSSortDescriptor 

sortDescriptorWithKey:@“book.name”,ascending:YES];

//2.先按照姓进行排序

NSSortDescriptor *lastNameDesc = [NSSortDescriptor 

sortDescriptorWithKey:@“lastname”,ascending:YES];


//3.先按照名进行排序

NSSortDescriptor *firstNameDesc = [NSSortDescriptor 

sortDescriptorWithKey:@firstname”,ascending:YES];


//按顺序添加排序描述器

NSArray *descs = [NSArray arrayWithObjects:bookNameDesc,lastnameDesc,firstnameDesc,nil];

NSArray *array2 = [array sortedArrayUsingDescriptors:descs];

NSLog(@“array2:%@”,array2);








以下为项目实践,同时使用了普通排序和高级排序功能;


定义一个学生类,需要有姓名,年龄,考试成绩三个成员属性,创建5个对象,属性可以任意值。(Objective-C)


1)    不使用@property,手动编写他们的访问器方法(getter和setter),注意内存管理(手动管理内存)
2)    增加一个便利构造器(快速构造器)
3)    使用NSLog输出学生对象时,输出信息格式为:My Name Is XXX  Age Is XXX Score Is XXX
4)    对5个学生对象按照成绩—》年龄—》姓名优先级排序(成绩相同按照年龄排序,成绩年龄相同按照姓名排序(5个学生的属性值自己随便设定,姓名不考虑中文,按26个大小字母排序))


student.h文件:

#import <Foundation/Foundation.h>@interface Student : NSObject{    NSString * _name;    int _age;    int _score;    }-(void)setName:(NSString*)name;-(void)setAge:(int)age;-(void)setScore:(int)score;-(NSString*)name;-(int)age;-(int)score;-(id)initName:(NSString*)name andAge:(int)age andScore:(int)score;+(id)studentName:(NSString *)name withAge:(int)age withScore:(int)score;-(NSComparisonResult)compareStuden:(Student *)stu;@end





student.m文件:

////  Student.m//  PersonStudent////  Created by xiaojunquan on 15/2/5.//  Copyright (c) 2015年 xiaojunquan. All rights reserved.//#import "Student.h"@implementation Student-(void)setName:(NSString *)name{    if (_name!=name) {        [_name release];        NSLog(@"%@被释放了",_name);        _name=[name retain];    }}-(void)setAge:(int)age{    _age=age;}-(void)setScore:(int)score{    _score=score;}-(NSString *)name{    return _name;}-(int)age{    return _age;}-(int)score{    return _score;}+(id)studentName:(NSString *)name withAge:(int)age withScore:(int)score{    Student *student =[[[Student alloc]init]autorelease];    student.name=name;    student.age=age;    student.score=score;    return  student;}-(id)initName:(NSString *)name andAge:(int)age andScore:(int)score{    if (self=[super init]){    self.age=age;    self.name=name;    self.score=score;    }    return self;}-(NSComparisonResult)compareStuden:(Student *)stu{    //将非oc对象(普通数据类型)封装成oc对象    NSNumber *score1 =[NSNumber numberWithInt:self.score];    NSNumber *score2 =[NSNumber numberWithInt:stu.score];    NSNumber *age1 = [NSNumber numberWithInt:self.age];    NSNumber *age2 = [NSNumber numberWithInt:stu.age];    //这里只能用oc对象来进行比较,不能写成self.score  compare: stu.score    NSComparisonResult result= [score1 compare: score2];    if (result==NSOrderedSame) {        result = [age1 compare: age2];        if (result== NSOrderedSame) {            result =  [self.name compare:stu.name];        }    }    return result;}-(NSString *)description{   // NSLog(@"My Name is @%,my age is i%,my score is i%",_name,_age,_score);   //切记不要写成i% @%    NSString *str= [NSStringstringWithFormat:@"My Name is %@ ,my age is %i ,my score is %i" ,self.name, self.age, self.score];    return  str;}-(void)dealloc{    [_name release];    NSLog(@"姓名为%@的学生被回收了。。。。",_name);    [super dealloc];    }@end

main.m文件中:

////  main.m//  PersonStudent////  Created by xiaojunquan on 15/2/5.//  Copyright (c) 2015年 xiaojunquan. All rights reserved.//#import <Foundation/Foundation.h>#import "Student.h"void sortStudent(NSArray *array){    //1.按分数从大到小排序    NSSortDescriptor *scoreDesc = [NSSortDescriptor sortDescriptorWithKey:@"score" ascending:NO];    //2.按年龄从大到小排序    NSSortDescriptor *ageDesc = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:NO];    //3.按姓名从小到大排序    NSSortDescriptor *nameDesc = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];    //4.按顺序填加描述器,用数组保存    NSArray *desc = [NSArray arrayWithObjects:scoreDesc,ageDesc,nameDesc, nil];    //5.让array 使用描述器来排序数组,因为nsarray是不可变的,所以存放在array2 中。    NSArray *array2= [array sortedArrayUsingDescriptors:desc];    //6.打印出排序结果    NSLog(@"array2:学生对象按照成绩—》年龄—》姓名优先级排序:%@",array2);}int main(int argc, const char * argv[]) {    @autoreleasepool {        // insert code here...        Student* stu1= [[Student alloc]initName:@"JJ" andAge:22 andScore:100];        Student* stu2= [[Student alloc]initName:@"YY" andAge:20 andScore:90];        Student* stu3= [[Student alloc]initName:@"ff" andAge:20 andScore:90 ];        Student* stu4= [[Student alloc]initName:@"dd" andAge:24 andScore:77];        Student* stu5= [[Student alloc]initName:@"bb" andAge:20 andScore:95];                Student *stu6= [Student studentName:@"anzi" withAge:22 withScore:100 ];                stu1.name = @"xiaojunquan";        NSArray *array = [NSArray arrayWithObjects:stu1,stu2,stu3,stu4,stu5,stu6, nil];        NSArray *array2 =[array sortedArrayUsingSelector:@selector(compareStuden:)];        NSLog(@"array2:学生对象按照成绩—》年龄—》姓名优先级排序:%@",array2);                  NSLog(@" 以下为高级方法排序:");        sortStudent(array);                [stu5 release];        [stu4 release];        [stu3 release];        [stu2 release];        [stu1 release];          }    return 0;}

最后运行结果如下:



我们看到排序结果都是按我们的要求来排列的,同时运用Foundation的高级方法和普通方法对student对象的NSArray数组元素进行排序。

并且最后结果没有内存泄漏。


0 0
原创粉丝点击