ios排序知识点函数

排序

Person.h

@interface Person : NSObject

{

    int _age;

    int _integrity;

    NSString * _name;

}

- (id)initWithAge:(int)age andWithIntegrity:(int)i andName:(NSString *)name;

@property (nonatomic) int age;

@property (nonatomic) int integrity;

//左边  大于 右边的准则

- (BOOL)olderThanIntegrity:(Person *)preson;

- (BOOL)youngerThanIntegrity:(Person *)person;



Person.m


#import "Person.h"


@implementation Person

@synthesize age = _age;

@synthesize integrity = _integrity;

- (id)initWithAge:(int)age andWithIntegrity:(int)i andName:(NSString *)name{


    if (self = [super init]) {

        _age = age;

        _integrity = i;

        _name = name;

    }

    return self;

}

//提供一个左边大于右边进行交换的准则  升序;

- (BOOL)olderThanIntegrity:(Person *)person{

//    if (self.integrity > person.integrity) {

//        return YES;

//    }else{

//        return NO;

//    }

  

    return self.integrity > person.integrity;

}


//降序

-  (BOOL)youngerThanIntegrity:(Person *)person{

    return self.integrity < person.integrity;

}


- (NSString *)description{

    NSString *str = [NSString stringWithFormat:@"name = %@ age = %d 节操 = %d",_name,_age,_integrity];

    return str;

}


@end




main


int main (int argc, const char * argv[])

{


    @autoreleasepool {

        

        Person *qiange = [[Person alloc]initWithAge:25 andWithIntegrity:0 andName:@"qiange"];

        Person *liangge = [[Person alloc]initWithAge:30 andWithIntegrity:-1 andName:@"liangge"];

        Person *laoGuo = [[Person alloc]initWithAge:30 andWithIntegrity:80 andName:@"laoguo"];

        Person *laoPan = [[Person alloc]initWithAge:30 andWithIntegrity:38 andName:@"laoPan"];

        Person *mars = [[Person alloc]initWithAge:35 andWithIntegrity:22 andName:@"mars"];

        Person *zhouXiang = [[Person alloc]initWithAge:40 andWithIntegrity:250 andName:@"zhouxiang"];

        

        NSMutableArray *array = [[NSMutableArray alloc]init];

        [array addObject:mars];

        [array addObject:laoGuo];

        [array addObject:qiange];

        [array addObject:zhouXiang];

        [array addObject:liangge];

        [array addObject:laoPan];

        //sortUsingSelector:这个是一个排序方法,已经实现了,但是缺少排序准则(升序/降序),(这个准则就是一个函数)

        //排序:数组元素应该是相同的对象指针类型

        //2.数组元素是哪个类的对象指针,那么我就把这个准则写到这个类中

        //3.这个准则就是什么时候交换???左边大于右边 交换还是    左边小于右边交换

        //升序

        [array sortUsingSelector:@selector(olderThanIntegrity:)];//@selector(olderThanIntegrity:)选择器  把函数名转化为选择器

        //相当于把olderThanIntegrity:传入sortUsingSelector:中;

        [array sortUsingSelector:@selector(youngerThanIntegrity:)];//降序

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

        

        

    }

    return 0;

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值