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
I can't think of a way to use a sort descriptor in the fetch request for that purpose. But you can sort the result array after fetching according to the indexes:
NSArray *sorted = [results sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NSUInteger idx1 = [indexes indexOfObject:[obj1 valueForKey:@"index"]];
NSUInteger idx2 = [indexes indexOfObject:[obj2 valueForKey:@"index"]];
return idx1 - idx2;
}];