首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NSArray的NSOrderedSet排序

NSArray的NSOrderedSet排序
EN

Stack Overflow用户
提问于 2013-03-25 14:45:45
回答 1查看 1.2K关注 0票数 1

我使用以下谓词执行NSFetchRequest

代码语言:javascript
复制
[NSPredicate predicateWithFormat:@"index IN %@", indexes];

..。其中indexes是数字的NSOrderedSet

这为我提供了一个具有给定索引的“随机排序”对象数组。我需要对此进行排序,以便使对象以与有序集相同的顺序出现。

做这件事最有效的方法是什么?

更新

以下是基于Martin R的回答的一个类别:

代码语言:javascript
复制
@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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-03-25 15:08:59

我想不出在fetch请求中使用排序描述符的方法。但是,您可以根据索引在获取后对结果数组进行排序:

代码语言:javascript
复制
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;
}];
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15617795

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档