本帖最后由 Micro 于 2015-2-14 22:45 编辑
- -(NSComparisonResult)compareStuden:(Student *)stu{
- //将非OC对象包装成OC对象
- NSNumber *score1 =[NSNumber numberWithInt:self.score];
- NSNumber *score2 =[NSNumber numberWithInt:stu.score];
- NSNumber *age1 = [NSNumber numberWithInt:self.age];
- NSNumber *age2 = [NSNumber numberWithInt:stu.age];
-
- NSComparisonResult result= [score1 compare: score2];
- if (result==NSOrderedSame) {
- result = [age1 compare: age2];
- if (result== NSOrderedSame) {
- result = [self.name compare:stu.name];
- }
- } return result;
- }
- -(NSString *)description{
- // NSLog(@"My Name is @%,my age is i%,my score is i%",_name,_age,_score);
- NSString *str= [NSString
- stringWithFormat:@"My Name is %@ ,my age is %i ,my score is %i" ,self.name, self.age, self.score];
- return str;
- }
- -(void)dealloc{
- [_name release];
- NSLog(@"姓名为%@的学生被回收了。。。。",_name);
- [super dealloc];
-
- }
复制代码- int main(int argc, const char * argv[]) {
- @autoreleasepool {
- // insert code here...
- Student* stu1= [[Student alloc]initName:@"JJ" andAge:22 andScore:100];
- Student* stu2= [[Student alloc]initName:@"YY" andAge:20 andScore:90];
- Student* stu3= [[Student alloc]initName:@"ff" andAge:20 andScore:90 ];
- Student* stu4= [[Student alloc]initName:@"dd" andAge:24 andScore:77];
- Student* stu5= [[Student alloc]initName:@"bb" andAge:20 andScore:95];
-
- Student *stu6= [Student studentName:@"anzi" withAge:22 withScore:100 ];
-
- stu1.name = @"xiaojunquan";
- NSArray *array = [NSArray arrayWithObjects:stu1,stu2,stu3,stu4,stu5,stu6, nil];
- NSArray *array2 =[array sortedArrayUsingSelector:@selector(compareStuden:)];
- NSLog(@"array2:学生对象按照成绩—》年龄—》姓名优先级排序:%@",array2);
-
- NSLog(@" 以下为高级方法排序:");
- sortStudent(array);
-
- [stu5 release];
- [stu4 release];
- [stu3 release];
- [stu2 release];
- [stu1 release];
-
- }
- return 0;
- }
复制代码
|
|