私は NSExpression メソッド expressionForFunction:arguments: を使用して、以下と同じコードで平均、合計、最小、最大、カウントに成功しました(Appleのドキュメントに記載されています)。
しかし、標準偏差 (stddev:) または中央値 (median:) に関しては。コンパイル中にエラーは発生しませんが、executeFetchRequest 行で "SIGABRT" シグナルを受け取るだけです。
私のコードでは、平均、合計、最小、最大、カウント、および標準偏差または中央値の違いが何であるかを見つけることができません。NSExpression クラスは、これらのパラメーターと戻りオブジェクトの間に違いはありません。唯一の違いは可用性です (動作しているものは Mac OS 10.4、その他は 10.5.
Xcode 4.2 を使用しており、アプリは ARC を使用して iOS 5 をターゲットにしています。
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"myEntity" inManagedObjectContext:app.managedObjectContext];
[request setEntity:entity];
[request setPredicate:[NSPredicate predicateWithFormat:@"something == %d",2]];
// Specify that the request should return dictionaries.
[request setResultType:NSDictionaryResultType];
// Create an expression for the key path.
NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"anAttribute"];
// Create an expression to represent the minimum value at the key path
NSExpression *statExpression = [NSExpression expressionForFunction:@"stddev:" arguments:[NSArray arrayWithObject:keyPathExpression]];
// Create an expression description using the statExpression and returning a float.
NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
// The name is the key that will be used in the dictionary for the return value.
[expressionDescription setName:@"statData"];
[expressionDescription setExpression:statExpression];
[expressionDescription setExpressionResultType:NSFloatAttributeType];
// Set the request's properties to fetch just the property represented by the expressions.
[request setPropertiesToFetch:[NSArray arrayWithObject:expressionDescription]];
// Execute the fetch.
NSError *error = nil;
NSArray *objects = [app.managedObjectContext executeFetchRequest:request error:&error];
if (objects == nil) {
// Handle the error.
}
float result = [[[objects objectAtIndex:0] valueForKey:@"statData"] floatValue];
ご協力いただきありがとうございます。