1.创立模型:Person类
#import <Foundation/Foundation.h>
@interface Person : NSObject
{
NSString*_name;
NSString*_sex;
CGFloat _score;
NSInteger _age;
}
-(void)setName:(NSString*)name;
-(void)setSex:(NSString*)sex;
-(void)setScore:(CGFloat)score;
-(void)setAge:(NSInteger)age;
-(NSString*)getName;
-(NSString*)getSex;
-(CGFloat)getScore;
-(NSInteger)getAge;
-(id)initWithName:(NSString*)name withSex:(NSString*)sex withScore:(CGFloat)score withAge:(NSInteger)age;
+(id)personWithName:(NSString*)name withSex:(NSString*)sex withScore:(CGFloat)score withAge:(NSInteger)age;
//自定义的类中重写排序方法
//外界只需要根据我们写好的排序规则排序即可
-(NSComparisonResult)compareWithAge:(Person*)person;
-(NSComparisonResult)compareWithName:(Person*)person;
@end
#import "Person.h"
@implementation Person
-(void)setName:(NSString*)name
{
_name = name;
}
-(void)setSex:(NSString*)sex
{
_sex = sex;
}
-(void)setScore:(CGFloat)score
{
_score =score;
}
-(void)setAge:(NSInteger)age
{
_age = age;
}
-(NSString*)getName
{
return _name;
}
-(NSString*)getSex
{
return _sex;
}
-(CGFloat)getScore
{
return _score;
}
-(NSInteger)getAge
{
return _age;
}
-(id)initWithName:(NSString*)name withSex:(NSString*)sex withScore:(CGFloat)score withAge:(NSInteger)age
{
if (self = [super init]) {
_name = name;
_sex = sex;
_age = age;
_score = score;
}
return self;
}
+(id)personWithName:(NSString *)name withSex:(NSString *)sex withScore:(CGFloat)score withAge:(NSInteger)age
{
Person*p = [[Person alloc]initWithName:name withSex:sex withScore:score withAge:age];
return p;
}
- (NSString *)description
{
return [NSString stringWithFormat:@"%@ %@ %0.2f %ld", _name,_sex,_score,_age];
}
#warning NSOrderedDescending是触发交换的条件(即某个判断条件下触发NSOrderedDescending则发生交换)
-(NSComparisonResult)compareWithAge:(Person*)person
{
if (_age>[person getAge] ) {
return NSOrderedDescending;
}else if (_age<[person getAge]){
return NSOrderedAscending;
}
return NSOrderedSame;
}
-(NSComparisonResult)compareWithName:(Person*)person
{
if ([_name compare:[person getName]] ==YES) {
return NSOrderedDescending;
}else if ([_name compare:[person getName]]==NO){
return NSOrderedAscending;
}
return NSOrderedSame;
}
@end
2.外面调用实现排序
Person*per1 = [Person personWithName:@"xueheng" withSex:@"male" withScore:92 withAge:25];
Person*per2 = [Person personWithName:@"zhanglizhi" withSex:@"male" withScore:88 withAge:27];
Person*per3 = [Person personWithName:@"liyanlie" withSex:@"male" withScore:87 withAge:23];
Person*per4 = [Person personWithName:@"wanghelin" withSex:@"male" withScore:91 withAge:26];
Person*per5 = [Person personWithName:@"mingming" withSex:@"male" withScore:76 withAge:22];
Person*per6 = [Person personWithName:@"aili" withSex:@"famale" withScore:82 withAge:25];
//不可变数组排序返回一个新的数组
NSMutableArray*array = [NSMutableArray arrayWithObjects:per1,per2,per3,per4,per5,per6, nil];
//自定义compare
[array sortUsingSelector:@selector(compareWithName:)];
NSLog(@"%@",array);