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; }
source share