I'm trying to write a simple function == " compareGPA" that compares between the GPA of two students , then sorting them in descending order by using selector as that : [array sortUsingSelector:@selector(compareGPA:)];
I've tried to write the function in 2 different ways , but nothing works ,
First way :
+(NSComparisonResult) compareGPA: (Student *) OtherStudent{
Student *tmp =[Student new];
if ([OtherStudent getGpa] < [tmp getGpa]){
return (NSComparisonResult) tmp;
}
if([tmp getGpa] < [OtherStudent getGpa])
{ return (NSComparisonResult) OtherStudent; }
}
2nd way :
+(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;
}
}
Output : Nothing
Any suggestions ??
You should make your caparison method
+(NSComparisonResult) compareGPA: (Student *) OtherStudent
an instance method (not a class method, + becomes -), so that it compares the receiver's GPA with OtherStudent's GPA), like this
-(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]]
}
Then sort your array of Student objects using selector @selector(compareGPA:)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With