2011-04-17 78 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