Search code examples
iosobjective-csortingnsarray

Bad receiver type error "float_nullable"


I'm trying to sort a NSMutableArray containing the following NSDictionaries:

{@"Student Name": John @"Average Test Score": 96.56}

{@"Student Name": Mary @"Average Test Score": 93.45} ......

The average scores are stored in NSDictionary as strings, so I'm using the following code:

NSArray *sortedResults = [studentResultsArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
return [[obj1[@"Average Test Score"] floatValue] compare:[obj2[@"Average Test Score"] floatValue]];}];

But I'm receiving the error prompt:Bad receiver type 'float _Nullable'

Can anyone tell me how to fix this problem, or is there other ways to sort the array?

Thank you!


Solution

  • The compare: method needs to be called on objects. You are trying to call it on a float value.

    Change this line:

    return [[obj1[@"Average Test Score"] floatValue] compare:[obj2[@"Average Test Score"] floatValue]];}];
    

    to:

    return [obj1[@"Average Test Score"] compare:obj2[@"Average Test Score"]];}];
    

    This way you call compare on the actual NSString objects.

    This change will fix the immediate problem but will present you with another problem. This will compare the two values as strings, not numbers.

    The proper solution to that is to store the averages as actual NSNumber instances, not as NSString instances.