如何比较Objects属性然后排序使用(sortusingselector:@selector)?

时间:2011-11-15 12:48:37

标签: objective-c

我正在尝试编写一个简单的函数==“compareGPA”,它比较两个学生的GPA,然后使用选择器按降序排序:[array sortUsingSelector:@selector(compareGPA :)];

我试图以两种不同的方式编写函数,但没有任何作用,

第一种方式:

+(NSComparisonResult) compareGPA: (Student *) OtherStudent{ 

Student *tmp =[Student new];

if ([OtherStudent getGpa] < [tmp getGpa]){

return (NSComparisonResult) tmp;

}

if([tmp getGpa] < [OtherStudent getGpa])

{ return (NSComparisonResult) OtherStudent; }


}

第二路:

+(NSComparisonResult) compareGPA: (Student *) OtherStudent{


NSComparisonResult res;


res = [[self getGpa] compare: [OtherStudent getGpa]];

return res;

Switch (res)
{

case NSOrderedAscending:

return NSOrderedDescending;

break;

case NSOrderedDescending:

return NSOrderedAscending;

break;

default:

return NSOrderedSame;

break;

}

}

输出:没什么

有什么建议吗?

2 个答案:

答案 0 :(得分:6)

你应该制作你的caparison方法

+(NSComparisonResult) compareGPA: (Student *) OtherStudent

实例方法(不是类方法,+变成 - ),以便它将接收者的GPA与OtherStudent的GPA进行比较),就像这样

-(NSComparisonResult) compareGPA: (Student *) OtherStudent {

     // if GPA is a float int double ...
     if ([OtherStudent getGpa] == [self getGpa] 
         return NSOrderedSame;
     if ([OtherStudent getGpa] < [self getGpa]){
         return NSOrderedAscending;
     return NSOrderedDescending;

     // if GPA is an object which responds to the compare: message
     return [[self getGPA] compare:[OtherStudent getGPA]]

}

然后使用选择器@selector(compareGPA:)

对您的Student对象数组进行排序

答案 1 :(得分:5)

当您正在使用compare:时,我必须假设getGPA返回NSNumber,在这种情况下,您只需要这样:

NSArray *students = ...;
NSArray *sortedStudents = [students sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"getGPa" ascending:NO]]];

如果getGPA要返回一些原始C类型(例如float),那么你可以这样做:

NSArray *students = ...;
NSArray *sortedStudents = [students sortedArrayUsingComparator:^NSComparisonResult(Studen *student1, Studen *student2) {
    float student1GPA = [student1 getGPA];
    float student2GPA = [student2 getGPA];
    if (student1GPA < student2GPA) {
        return NSOrderedAscending;
    } else if (student1GPA > student2GPA) {
        return NSOrderedDescending;
    }
    return NSOrderedSame;
}];

如果您在其他地方也需要compareGPA:

- (NSComparisonResult) compareGPA:(Studen *otherStudent) {
    float student1GPA = [self getGPA];
    float student2GPA = [otherStudent getGPA];
    if (student1GPA < student2GPA) {
        return NSOrderedAscending;
    } else if (student1GPA > student2GPA) {
        return NSOrderedDescending;
    }
    return NSOrderedSame;
}