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

---------- 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= [NSString
stringWithFormat:@"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
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值