Data结果进行排序

Data结果进行排序

本文介绍了如何根据相关对象集合的属性对Core Data结果进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

设置:我有一个父对象的集合,称为ObjectA。每个ObjectA都有一个到ObjectB的一对多关系。因此,一个ObjectA可能包含0..n ObjectB-s,每个ObjectB都有一个特定的ObjectA作为其父类。

Setup: I have a collection of parent objects, call them ObjectA. Each ObjectA has a one-to-many relation to ObjectB. So, one ObjectA may contain 0..n ObjectB-s, and each ObjectB has a specific ObjectA as its parent.

现在,我想做一个核心数据fetch ObjectA-s,在那里按最新的ObjectB排序。是否可以为此创建一个排序描述符?

Now, I would like to do a Core Data fetch of ObjectA-s, where they are sorted by their latest ObjectB. Is it possible to create a sort descriptor for that?

有,描述完全相同的情况。答案建议将属性从ObjectB反规范化为ObjectA。

There is a related question that describes exactly the same situation. The answer suggests denormalizing the attribute from ObjectB into ObjectA. This would be OK if there really is no way to do this with one fetch request.

相关问题也提到:

我试过。它似乎不可能。我收到此错误:

I tried. It doesn’t seem to be possible. I get this error:

2012-10-05 17:51:42.813 xxx[6398:c07] *** Terminating app due to uncaught
exception 'NSInvalidArgumentException', reason: 'Keypath containing
KVC aggregate where there shouldn't be one; failed to handle
[email protected]'

将属性反规范化为ObjectA只有/最好的解决方案?

Is denormalizing the attribute into ObjectA the only/best solution?

推荐答案

我知道这个问题有点老,但我做的是获取所有ObjectB,结果并拉出ObjectB属性并将其添加到新数组中。

I know this question is a bit old but what I did was get all ObjectBs, iterate over the results and pull out the ObjectB property and add it to a new array.

NSFetchRequest *fetchRequest = [NSFetchRequest new];
[fetchRequest setEntity:self.entityDescForObjectB];

// sort
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:YES];
[fetchRequest setSortDescriptors:@[sortDescriptor]];

NSError *error = nil;
NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects == nil) {
    NSLog(@"Error fetching objects: %@", error.localizedDescription);
    return;
}

// pull out all the ObjectA objects
NSMutableArray *tmp = [@[] mutableCopy];
for (ObjectB *obj in fetchedObjects) {
    if ([tmp containsObject:obj.objectA]) {
        continue;
    }
    [tmp addObject:obj.objectA];
}

这是因为CoreData是一个对象图,所以你可以倒退。在结尾的循环基本上检查 tmp 数组是否已经有一个特定的ObjectA实例,如果没有添加到数组。

This works because CoreData is an object graph so you can work backwards. The loop at the end basically checks to see if the tmp array already has a specific ObjectA instance and if not adds it to the array.

重要的是你对ObjectB进行排序,否则这个练习是无意义的。

It's important that you sort the ObjectBs otherwise this exercise is pointless.

这篇关于如何根据相关对象集合的属性对Core Data结果进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 17:22