本文介绍了使用SortDescriptor和谓词对NSMutableArray进行排序可能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个类型为"Restaurant"的数组,其NSSet为"Rating".评分有一个ID和一个值.
I have an array of type "Restaurant" which has an NSSet of "Rating." Rating has an ID and a value.
我想按ID(从高到低)的ID对餐厅的数组进行排序.
I want to sort the array of Restaurant's by rating with an ID of 01, from high to low.
类似以下内容,但是如何在originalArray上同时使用谓词和排序描述符?
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]];
推荐答案
您可以使用NSComparator
块对数组进行排序.
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;
}];
这篇关于使用SortDescriptor和谓词对NSMutableArray进行排序可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!