I'm doing an NSFetchRequest
with the following predicate:
[NSPredicate predicateWithFormat:@"index IN %@", indexes];
... where indexes
is an NSOrderedSet
of numbers.
This gives me an array of "randomly sorted" objects with given indexes. I need to sort this so that the objects appear in the same order as in the ordered set.
What would be the most efficient way to do this?
Update
Here is a category based on Martin R's answer:
@implementation NSArray (SortUsingValues)
- (NSArray *)sortedArrayUsingValues:(NSOrderedSet *)values keyPath:(NSString *)keyPath
{
NSAssert([values isKindOfClass:[NSOrderedSet class]], nil);
NSAssert([keyPath isKindOfClass:[NSString class]], nil);
return [self sortedArrayUsingComparator:^NSComparisonResult(id object, id otherObject) {
id value = [object valueForKeyPath:keyPath];
id otherValue = [otherObject valueForKeyPath:keyPath];
NSUInteger indexOfValue = [values indexOfObject:value];
NSUInteger indexOfOtherValue = [values indexOfObject:otherValue];
if (indexOfValue > indexOfOtherValue) return NSOrderedDescending;
else if (indexOfValue < indexOfOtherValue) return NSOrderedAscending;
else return NSOrderedSame;
}];
}
@end