Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting NSMutableArray using SortDescriptor AND Predicate possible?

I have an array of type "Restaurant" which has an NSSet of "Rating." Rating has an ID and a value.

I want to sort the array of Restaurant's by rating with an ID of 01, from high to low.

Something like the following, but how do I use the predicate and sort descriptor together on originalArray?

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"Rating.rating_id=%d", ratingID];
NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@"currentValue" ascending:YES];
NSArray *sorted = [[originalArray allObjects] sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptor]];
like image 240
Oh Danny Boy Avatar asked Dec 22 '11 18:12

Oh Danny Boy


1 Answers

You can sort the array using a NSComparator block.

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"rating_id = %d", ratingID];

NSArray *sorted = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {

    int value1 = [[[[obj1 ratings] filteredSetUsingPredicate:predicate] anyObject] currentValue];
    int value2 = [[[[obj2 ratings] filteredSetUsingPredicate:predicate] anyObject] currentValue];

    if ( value1 < value2 )
        return NSOrderedAscending;
    if ( value1 > value2 )
        return NSOrderedDescending;
    return NSOrderedSame;
}];
like image 106
Nicolas Bachschmidt Avatar answered Oct 11 '22 17:10

Nicolas Bachschmidt