2

the problem im having is that i cant sort an NSMutableArray of NSMutableDictionary Objects, I want to sort the objects by rating, the rating is a NSNumber, what am i missing?

My current code that sums all the ratings from "arrayMealRating" and sorts the resulting array:

            [arrayMealRating addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
                                        [eachObject objectForKey:@"Airline"], @"Airline"
                                        ,[eachObject objectForKey:@"setMealRating"], @"setMealRating"
                                        , nil]];

        }
        NSArray *airlineNames = [arrayMealRating valueForKeyPath:@"@distinctUnionOfObjects.Airline"];

        // Loop through all the airlines
        for (NSString *airline in airlineNames) {

            // Get an array of all the dictionaries for the current airline
            NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(Airline == %@)", airline];
            NSArray *airlineMealRating = [arrayMealRating filteredArrayUsingPredicate:predicate];

            // Get the sum of all the ratings using KVC @sum collection operator
            NSNumber *rating = [airlineMealRating valueForKeyPath:@"@sum.setMealRating"];

            //NSLog(@"%@: %@", airline, rating);
            [sortedMealArray addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
                                        airline, @"Airline"
                                        ,[rating stringValue], @"setMealRating"
                                      , nil]];
        }



        NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"setMealRating"  ascending:YES];
        [sortedMealArray sortedArrayUsingDescriptors:[NSMutableArray arrayWithObjects:descriptor,nil]];
        auxMealRating = [sortedMealArray copy];

Any doubt, please dont down vote, just ask and i will edit the question.

Best Regards and sorry for my poor english.

1 Answer 1

4

This should do what you want:

NSArray *sortedArray = [arrayMealRating sortedArrayUsingComparator:^(id obj1, id obj2) {
    NSNumber *rating1 = [(NSDictionary *)obj1 objectForKey:@"setMealRating"];
    NSNumber *rating2 = [(NSDictionary *)obj2 objectForKey:@"setMealRating"];
    return [rating1 compare:rating2];
}];
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks it worked :) has a side note can it be sorted by NSOrderedAscending? is yes how?
@BrunoVasconcelos Yes, just reverse rating1 compare:rating2 to rating2 compare:rating1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.