CoreData:使用IN对基于谓词/数组的排序进行排序

时间:2012-01-13 21:07:35

标签: sorting core-data nspredicate

我有一个CoreData商店,我希望维护一个REST服务提供的排序顺序。 CoreData中的对象具有guid属性,并且REST提供的数组(GUID)已排序。我想在从CoreData获取对象后保持这种排序。

我在获取中使用了以下NSPredicate

[NSPredicate predicateWithFormat:@"guid IN %@", wishlistGUIDs];

其中wishlistGUIDs是REST为相关对象提供的GUID数组。

有没有办法在保持wishlistGUIDs订单的同时获取结果?我已经探索过使用NSSortDescriptor,并通过迭代wishlistGUIDs来组装一个疯狂的排序描述符数组,但它似乎过于复杂而且只是“错误的”。

2 个答案:

答案 0 :(得分:0)

你可以限制自己使用iOS 5 / Lion吗?对于有序关系(以NSOrderedSet形式出现),这看起来是一个很好的用例。你有一个核心数据实体“愿望清单”,它将包含有序的GUID。

除此之外,我认为你必须做一些丑陋的事情,比如为GUID列表维护你自己的序列号。

答案 1 :(得分:0)

以下是解决此类问题的额外步骤:

定义方法:

NSInteger gidSort(Guild* num1, Guild* num2, void *context) {
    NSArray* wishlistGUIDs = (NSArray*)context;
    int v1 = [wishlistGUIDs indexOfObject:num1.guid];
    int v2 = [wishlistGUIDs indexOfObject:num2.guid];
    if (v1 < v2)
        return NSOrderedAscending;
    else if (v1 > v2)
        return NSOrderedDescending;
    else
        return NSOrderedSame;
}

然后从获取结果获得结果:

NSArray* resorted = [results sortedArrayUsingFunction:gidSort context:wishlistGUIDs];
相关问题