2012-10-05 67 views
6

安装程序:我有一个父对象的集合,称它们为ObjectA。每个ObjectA与ObjectB都有一对多的关系。所以,一个ObjectA可以包含0..n ObjectB-s,每个ObjectB都有一个特定的ObjectA作为它的父节点。如何根据相关对象集合的属性对核心数据结果进行排序?

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

a related question描述完全相同的情况。答案建议将ObjectB中的属性非规范化为ObjectA。如果真的没有办法通过一个获取请求来做到这一点,那就没问题了。

的相关问题也提到:

Actually, I just had an idea! Maybe I can sort Conversations by [email protected]

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

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]' 

是反规范化的属性到对象A的唯一/最好的解决办法?

回答

0

您可以添加在对象B的属性,它是将日期的时间戳记,然后获取请求,你可以做这样的事情:

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

这对我不起作用: 'NSInvalidArgumentException',原因:'对多关键不允许在这里' –

0

我知道这个问题是有点老,但什么我所做的是获取所有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实例,如果没有将它添加到数组中。

排序ObjectBs是非常重要的,否则这个练习是毫无意义的。

相关问题