Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/wcf/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Core data 如何根据相关对象集合的属性对核心数据结果进行排序?_Core Data_Nssortdescriptor - Fatal编程技术网

Core data 如何根据相关对象集合的属性对核心数据结果进行排序?

Core data 如何根据相关对象集合的属性对核心数据结果进行排序?,core-data,nssortdescriptor,Core Data,Nssortdescriptor,设置:我有一个父对象集合,称它们为ObjectA。每个ObjectA都与ObjectB有一对多关系。因此,一个ObjectA可能包含0..n ObjectB-s,每个ObjectB都有一个特定的ObjectA作为其父对象 现在,我想对ObjectA-s进行一次核心数据提取,在这里,它们按照最新的ObjectB进行排序。是否可以为此创建排序描述符 有一种说法完全描述了同样的情况。答案建议将属性从ObjectB反规范化为ObjectA。如果真的没有办法通过一个获取请求来实现这一点,那么这就可以了 相

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

现在,我想对ObjectA-s进行一次核心数据提取,在这里,它们按照最新的ObjectB进行排序。是否可以为此创建排序描述符

有一种说法完全描述了同样的情况。答案建议将属性从ObjectB反规范化为ObjectA。如果真的没有办法通过一个获取请求来实现这一点,那么这就可以了

相关问题还提到:

事实上,我刚刚有个主意!也许我可以按消息对对话进行排序。@max.sortedDate

我试过了。这似乎不可能。我得到这个错误:

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
ObjectB.@max.creationTime'

将属性反规范化为ObjectA是唯一/最佳的解决方案吗?

您可以在ObjectB中添加一个属性,该属性是添加日期的时间戳,然后在获取请求中执行以下操作:

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"objectB.addTime" ascending:YES];
...
fetchRequest.sortDescriptors = @[descriptor];

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

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实例,如果没有,则将其添加到数组中


对ObjectB进行排序很重要,否则此练习毫无意义。

这对我不起作用:“NSInvalidArgumentException”,原因:“此处不允许使用多个键”