私の人生では、これを機能させることができないようです。
エンティティがステータスフィールドと注文フィールドを持つ管理対象オブジェクトであると想定します。
同じ注文が複数あるすべてのorderedEntriesを取得するにはどうすればよいですか?
メイン述語に@countを使用してサブクエリを実行するように指示する回答はありません。その解決策を知っているので、この投稿のポイントは、コアデータで持つ述語を使用する方法を理解することです。とにかくサブクエリ。(私がhave句を使用できない理由を説明しない限り)
次のコードは、注文番号ごとの注文数を含む辞書の配列を返します。私が欲しいのは、1より大きいカウントを持つ注文のオブジェクトを表すディクショナリのみを返すように要求を制限するために、have句を追加できるようにすることです。
これまでのコードと、述語を持つことを試みた私の試みは次のとおりです。
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"OrderedEntry"
inManagedObjectContext:context];
[fetchRequest setEntity:entity];
[fetchRequest setResultType:NSDictionaryResultType];
NSPredicate *predicate = [NSPredicate predicateWithFormat:
@"(status == %@)",[NSNumber numberWithInt:EntryStatusAlive]];
[fetchRequest setPredicate:predicate];
NSExpression *keyPathExpression = [NSExpression expressionForKeyPath: @"order"]; // Does not really matter
NSExpression *maxExpression = [NSExpression expressionForFunction: @"count:"
arguments: [NSArray arrayWithObject:keyPathExpression]];
NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
[expressionDescription setName: @"orderCount"];
[expressionDescription setExpression: maxExpression];
[expressionDescription setExpressionResultType: NSInteger32AttributeType];
[fetchRequest setPropertiesToFetch: [NSArray arrayWithObjects:expressionDescription,@"order",nil]];
[fetchRequest setPropertiesToGroupBy:[NSArray arrayWithObjects:@"order",nil]];
//[fetchRequest setHavingPredicate:[NSPredicate predicateWithFormat:@"@count > 1"]];
//[fetchRequest setHavingPredicate:[NSComparisonPredicate predicateWithLeftExpression:maxExpression rightExpression:[NSExpression expressionForConstantValue:[NSNumber numberWithInteger:1]] modifier:NSDirectPredicateModifier type:NSGreaterThanPredicateOperatorType options:NSCaseInsensitivePredicateOption]];
NSError *error;
NSArray * array = [context executeFetchRequest:fetchRequest error:&error];