4

こんにちは、リレーションシップでオブジェクトを注文できる FetchRequest を指定する方法を知りたいです。

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

たとえば、位置属性を含む親テーブルがあり、位置属性も持つ子テーブルと 1 対多の関係があるとします。位置順の子オブジェクトを含む親オブジェクト (位置順) を返すにはどうすればよいですか。

例えば

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

1 に答える 1

4

これには 2 つの戦略があります。

  1. NSSortDescriptor を使用して、子に対して個別のフェッチ要求を実行します。プロ: これを FetchController に保持します。短所: 複数のフェッチ リクエストにより速度が低下する可能性があります
  2. 返された子を NSArray*parentThatContainChildren で並べ替えます。

#2については、これを確認できます:

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

NSArray *children = [[parent.children allObjects] sortedArrayUsingDescriptors:[NSArray arrayWithObject:positionSort]];
于 2011-04-17T13:15:06.983 に答える