我有一个类型为“餐厅”的数组,它的NSSet为“等级”。评级有ID和值。
我想通过ID为01,从高到低的等级对餐厅的数组进行排序。
如下所示,但如何在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]];
答案 0 :(得分:5)
您可以使用NSComparator
块对数组进行排序。
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;
}];