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

moh*_*lem 4 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; }


}
Run Code Online (Sandbox Code Playgroud)

第二种方式:

+(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;

}

}
Run Code Online (Sandbox Code Playgroud)

输出:没什么

有什么建议 ??

jba*_*100 6

你应该制作你的caparison方法

+(NSComparisonResult) compareGPA: (Student *) OtherStudent
Run Code Online (Sandbox Code Playgroud)

一个实例方法(不是类方法,+变成 - ),以便它将接收者的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]]

}
Run Code Online (Sandbox Code Playgroud)

然后使用selector对您的Student对象数组进行排序 @selector(compareGPA:)


Reg*_*ent 5

当你使用时compare:我必须假设getGPA返回一个NSNumber,在这种情况下,你需要的只是:

NSArray *students = ...;
NSArray *sortedStudents = [students sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"getGPa" ascending:NO]]];
Run Code Online (Sandbox Code Playgroud)

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;
}];
Run Code Online (Sandbox Code Playgroud)

如果您还需要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;
}
Run Code Online (Sandbox Code Playgroud)