Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Compare between Objects property's then sort using ( sortusingselector:@selector)?

Tags:

objective-c

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 ??

like image 337
mohamed salem Avatar asked Dec 22 '22 06:12

mohamed salem


1 Answers

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:)

like image 156
jbat100 Avatar answered May 15 '23 22:05

jbat100