【问题标题】:How to sort Core Data results based on an attribute of related object collection?如何根据相关对象集合的属性对 Core Data 结果进行排序?
【发布时间】:2012-10-05 14:55:39
【问题描述】:

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

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

a related question 描述了完全相同的情况。答案建议将属性从 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 是唯一/最好的解决方案吗?

【问题讨论】:

    标签: core-data nssortdescriptor


    【解决方案1】:

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

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

    【讨论】:

    • 这对我不起作用:“NSInvalidArgumentException”,原因:“此处不允许使用多对多键”
    【解决方案2】:

    我知道这个问题有点老了,但我所做的是获取所有 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 进行排序很重要,否则这个练习毫无意义。

    【讨论】:

      猜你喜欢
      • 2011-03-29
      • 2012-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多