[示例-NSArray排序]-根据班级、姓名和年龄排序学生信息
main:
1 #import <Foundation/Foundation.h> 2 #import "Person.h" 3 4 int main(int argc, const char * argv[]) { 5 @autoreleasepool { 6 Person *stu1=[[Person alloc]initClasses:@"iOS8" andName:@"ZXY" andAge:21]; 7 Person *stu2=[[Person alloc]initClasses:@"iOS6" andName:@"HYU" andAge:28]; 8 Person *stu3=[[Person alloc]initClasses:@"iOS8" andName:@"AWE" andAge:25]; 9 Person *stu4=[[Person alloc]initClasses:@"iOS6" andName:@"MKI" andAge:23]; 10 Person *stu5=[[Person alloc]initClasses:@"iOS8" andName:@"BYU" andAge:24]; 11 NSArray *arr=[NSArray arrayWithObjects:stu1,stu2,stu3,stu4,stu5,nil]; //将实例化的对象放入数组中 12 NSArray *sortArr1=[arr sortedArrayUsingSelector:@selector(compareWithClassAndName:)]; //将排序后的数组存入到新数组sortArr中 13 //NSLog(@"%@",sortArr1); //采用description输出 14 for (Person *person in sortArr1){ 15 NSLog(@"姓名:%@,班级:%@,年龄:%d",person.name,person.classes,person.age); 16 } 17 NSArray *sortArr2=[arr sortedArrayUsingSelector:@selector(compareWithAge:)]; //按年龄排序 18 for(Person *person in sortArr2){ 19 NSLog(@"姓名:%@,班级:%@,年龄:%d",person.name,person.classes,person.age); 20 } 21 } 22 return 0; 23 }
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 -(NSComparisonResult)compareWithClassAndName:(Person *)person; //比较姓名和班级 9 -(NSComparisonResult)compareWithAge:(Person *)person; //比较年龄 10 @end
Person.m:
1 #import "Person.h" 2 3 @implementation Person 4 -(instancetype)initClasses:(NSString *)classes andName:(NSString *)name andAge:(int)age; //初始化数据 5 { 6 Person *person=[[Person alloc]init]; 7 person.classes=classes; //给classes赋值,后面的classes为主函数中实例化的数据传进来的形参 8 person.name=name; 9 person.age=age; 10 return person; 11 } 12 -(NSComparisonResult)compareWithClassAndName:(Person *)person; //比较姓名和班级 13 { 14 NSComparisonResult result=[self.classes compare:person.classes]; //比较本类中的classes和传进来的classes 15 if(result==NSOrderedSame){ 16 return [self.name compare:person.name]; //返回比较值 17 } 18 else{ 19 return result; 20 } 21 } 22 -(NSComparisonResult)compareWithAge:(Person *)person; //比较年龄 23 { 24 if(self.age==person.age){ 25 return NSOrderedSame; 26 } 27 else if(self.age>person.age){ 28 return NSOrderedDescending; 29 } 30 else{ 31 return NSOrderedAscending; 32 } 33 } 34 -(NSString *)description{ //重写description使打印出来的带有格式 35 return [NSString stringWithFormat:@"Class:%@ Name:%@ Age:%d",self.classes,self.name,self.age]; //格式化输出 36 } 37 @end
(以上代码在Xcode 6.4中编译运行正常)