How to compare property of objects and then sort (sortusingselector: @selector)?

I am trying to write a simple function == compareGPA that compares between students two GPAs and then sorts them in descending order using the selector: [array sortUsingSelector: @selector (compareGPA :)];

I tried to write a function in two 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; } } 

The second 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

+4
source share
2 answers

You have to make your caparison method

 +(NSComparisonResult) compareGPA: (Student *) OtherStudent 

instance method (not class method, + becomes -), so that it compares the recipient's GPA with the OtherStudent GPU), 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 the array of Student objects using the @selector(compareGPA:) selector

+6
source

As you use compare: I have to assume that getGPA returns NSNumber , in which case you will need the following:

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

If getGPA was supposed to return some type of C primitive (e.g. float in your case), you could do it like this:

 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; }]; 

If you need compareGPA: elsewhere:

 - (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; } 
+5
source

Source: https://habr.com/ru/post/1381293/


All Articles