oc之类排序
根据学生班级 ,姓名,年龄进行排序,若班级相同,则按照姓名进行排序
示例代码:
main.m
1 #import <Foundation/Foundation.h> 2 #import "Person.h" 3 #define NSLog(FORMAT, ...) printf("%s\n", [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String]) 4 5 int main(int argc, const char * argv[]) { 6 @autoreleasepool { 7 Person *stu1=[[Person alloc]initClasses:@"IOS8" 8 andName:@"ZXY" 9 andAge:22]; 10 Person *stu2=[[Person alloc]initClasses:@"IOS8" 11 andName:@"ASD" 12 andAge:24]; 13 Person *stu3=[[Person alloc]initClasses:@"IOS7" 14 andName:@"JYC" 15 andAge:21]; 16 Person *stu4=[[Person alloc]initClasses:@"IOS7" 17 andName:@"GFD" 18 andAge:23]; 19 NSArray *arr=[NSArray arrayWithObjects:stu1,stu2,stu3,stu4,nil]; 20 21 NSArray *sortArr=[arr sortedArrayUsingSelector:@selector(compareWithClassAndName:)]; 22 for(Person *person in sortArr){ 23 NSLog(@"班级%@ 姓名%@ 年龄%d",person.classes,person.name,person.age); 24 } 25 NSLog(@"%@",sortArr); 26 27 } 28 return 0; 29 }
person.h
1 #import <Foundation/Foundation.h> 2 3 @interface Person : NSObject 4 @property NSString *classes; 5 @property NSString *name; 6 @property int age; 7 -(instancetype)initClasses:(NSString *)classes andName:(NSString *)name andAge:(int)age; 8 //instancetype 返回输入的对象 instancetype 可以反回和方法所在类相同类型的对象 9 -(NSComparisonResult)compareWithClassAndName:(Person *)person; 10 -(NSComparisonResult)compareWithAge:(Person *)person; 11 12 @end
person.m
#import "Person.h" @implementation Person -(instancetype)initClasses:(NSString *)classes andName:(NSString *)name andAge:(int)age{ Person *person=[[Person alloc]init]; person.classes=classes; person.name=name; person.age=age; return person; } -(NSComparisonResult)compareWithClassAndName:(Person *)person{ NSComparisonResult result=[self.classes compare:person.classes]; if(result==NSOrderedSame){ return [self.name compare:person.name];//如果班级相同,则返回姓名排序的结果 }else{ return result; //如果班级不同,则返回班级排序结果 } } -(NSComparisonResult)compareWithAge:(Person *)person{ if(self.age==person.age){ return NSOrderedSame; }else if(self.age>person.age){ return NSOrderedDescending; }else{ return NSOrderedAscending; } } -(NSString *)description{ return [NSString stringWithFormat:@"class:%@ name:%@ age:%d",self.classes,self.name,self.age]; } @end