【发布时间】:2013-03-15 02:39:22
【问题描述】:
我正在使用以下谓词执行NSFetchRequest:
[NSPredicate predicateWithFormat:@"index IN %@", indexes];
...其中indexes 是一个NSOrderedSet 的数字。
这给了我一个具有给定索引的“随机排序”对象数组。我需要对此进行排序,以便对象以与有序集中相同的顺序出现。
最有效的方法是什么?
更新
这是基于 Martin R 回答的类别:
@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
【问题讨论】:
标签: cocoa core-data nsarray nssortdescriptor nsorderedset