2011-04-17 79 views
4

您好想知道如何指定一个FetchRequest,我可以在一个关系中排序对象。ios NSFetchRequest,订购子对象

| Parent   |  | Child  | 
    |  - name  |------->| - name  | 
    |  - position |  | - position | 

举例来说,如果我有一个包含一个位置属性,并有一个与具有也有一个位置属性的子表上有许多关系的父表。如何返回包含按位置排序的子对象的父对象(按位置排序)。

parent 1 
    child 1 
    child 2 
    child 3 

parent 2 
    child 15 
    child 16 

parent 3 
    child 22 
    child 23 
    child 24 

显然,下面的代码将责令父对象正确的,但我怎么会做出与每个父母返回的子对象要以正确的顺序

NSFetchRequest* fetchReqest = [[NSFetchRequest alloc] init]; 

    NSEntityDescription* entity = [NSEntityDescription entityForName:@"parent" inManagedObjectContext:managedObjectContext]; 
    [fetchReqest setEntity:entity]; 

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] 
             initWithKey:@"position" ascending:YES]; 
    [fetchReqest setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]]; 
    [sortDescriptor release]; 

    NSArray* parentsThatContainChildren = [managedObjectContext executeFetchRequest:fetchReqest error:nil]; 

干杯

回答

4

有2种策略:

  1. 使用NSSortDescriptor为孩子执行单独的提取请求。 Pro:你把它放在FetchController中。骗局:多个提取请求可能会减慢您的速度
  2. 对NSArray * parentsThatContainChildren中返回的子项进行排序。

#2,您可以check this out

NSSortDescriptor *positionSort = [NSSortDescriptor sortDescriptorWithKey:@"position" ascending:YES]; 

NSArray *children = [[parent.children allObjects] sortedArrayUsingDescriptors:[NSArray arrayWithObject:positionSort]]; 
+0

真棒。谢谢您的帮助。 – user346443 2011-04-17 13:28:43

+0

第二个策略很好。感谢您的建议! – 2012-06-21 08:20:58