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;

}



你可能感兴趣的:(IOS琐碎知识点,排序)