1

高低を検索しましたが、探しているものを正確に見つけることができませんでした。私の質問はこれに似ていますが、少し異なります:

コア データ - 関連レコードの数

Person エンティティと 1 対多の関係を持つ Car エンティティがあるとします。これは、複数の人が車を運転できることを意味しますが、各人は 1 台の車しか運転しません。

次のことを達成できる述語を1つだけ実行できるようにしたい:

  1. 「赤」のすべての車。
  2. 一致する車の 'Year' および 'Color' 属性のみを返します。
  3. この車を運転している人の数を返します (つまり、結果として得られる各車内の People の NSSet のサイズ)。

これらすべてを 1 つのクエリで実行することは可能ですか?

複数のクエリでこれを行う方法を知っています。setPropertiesToFetch上記の 1 と 2 を実現するには、フィルター処理された述語を使用して使用するだけです。次に、すべての車の Persons エンティティに対して別のカウント クエリ ( countForFetchRequest) を実行して、各車を運転する Person(s) の数を調べます。

重要なのは、上記の 3 番目の要件です。すべてを 1 つの述語で実行したいのですが、最初のクエリですべての Person エンティティ オブジェクトをメモリ (パフォーマンス) に取り込みたくありません。countForFetchRequestさらに、車ごとに別のクエリを呼び出すのは面倒です。

これを行う最善の方法は何ですか?

ありがとう!

4

2 に答える 2

3
  1. 「赤い」車のみを返す:

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"color LIKE 'red'"];
    
  2. この車を運転している人数を返します。

    NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"people"];
    NSExpression *countExpression = [NSExpression expressionForFunction:@"count:"
                                                              arguments:@[keyPathExpression]];
    
    NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
    [expressionDescription setName:@"count"];
    [expressionDescription setExpression:countExpression];
    [expressionDescription setExpressionResultType:NSInteger32AttributeType];
    
  3. 「年」属性と「色」属性 (およびカウント) のみを返します。

    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Car"
                                              inManagedObjectContext:context];
    
    NSDictionary *attributes = [entity attributesByName];
    
    NSArray *properties = @[expressionDescription, attributes[@"year"], attributes[@"color"]];
    
  4. フェッチ リクエストをビルドして実行します。

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entity];
    [request setResultType:NSDictionaryResultType];
    
    [request setPropertiesToFetch:properties]; // return only count, year & color
    
    [request setPredicate:predicate]; // return only red cars
    
    NSError *error = nil;
    NSArray *results = [context executeFetchRequest:request error:&error];
    
  5. 結果を処理します。

    if (results) {
        for (NSDictionary *result in results) {
            NSLog(@"Year: %@", result[@"year"]);
            NSLog(@"Color: %@", result[@"color"]);
            NSLog(@"Drivers: %@", result[@"count"]);
        }
    }
    else {
        NSLog(@"Error: %@", error);
    }
    
于 2013-08-26T03:05:24.280 に答える