0

max、min、avg などは問題なく計算できます。

NSExpression *maxDate = [NSExpression expressionForKeyPath:@"startDate"];
NSExpression *maxDateExpression = [NSExpression expressionForFunction:@"max:"
                                                            arguments:@[maxDate]];
NSExpressionDescription *maxDateExpressionDescription = [[NSExpressionDescription alloc] init];
[maxDateExpressionDescription setName:@"maxDate"];
[maxDateExpressionDescription setExpression:maxDateExpression];
[maxDateExpressionDescription setExpressionResultType:NSDateAttributeType];



[request setPropertiesToFetch:@[maxDateExpressionDescription]];


// Execute the fetch.
NSError *error = nil;

NSArray *objects = [context executeFetchRequest:request error:&error];
if (error) {
    // Handle the error.

    NSLog(@"Error!");
}
else {
    NSLog(@"Max date is: %@", [objects[0] objectForKey:@"maxDate"]);
]

しかし、購入した価格と属性として販売した価格を持つ "Item" エンティティがある場合、NSExpressions を使用してすべての Item エンティティの合計 Profit を計算するにはどうすればよいでしょうか?

ありがとうございました

4

1 に答える 1

1

次の式の説明は、各オブジェクトの価格差を計算します。

NSExpression *price1Expr = [NSExpression expressionForKeyPath:@"price1"];
NSExpression *price2Expr = [NSExpression expressionForKeyPath:@"price2"];
NSExpression *profitExpr = [NSExpression
                                    expressionForFunction:@"from:subtract:"
                                    arguments:@[price2Expr, price1Expr]];

NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
[expressionDescription setName:@"profit"];
[expressionDescription setExpression:profitExpr];
[expressionDescription setExpressionResultType:NSDoubleAttributeType];

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Entity"];
[request setPropertiesToFetch:@[expressionDescription]];
[request setResultType:NSDictionaryResultType];
NSArray *profits = [context executeFetchRequest:request error:&error];
NSLog(@"%@", profits);

EDIT:(上記の回答を書いている間に質問が編集されました。)単一のフェッチリクエストでは、すべての価格差の合計を計算することはできないようです。たとえば、コアデータで計算を実行するための連鎖式を参照してください。ただし、上記の式の説明を使用して、すべての価格差の配列をフェッチし、Key-Value コーディングを使用して合計を計算できます。

NSArray *profits = result of fetch request
NSNumber *totalProfit = [profits valueForKeyPath:@"@sum.profit"];
NSLog(@"%@", totalProfit);
于 2013-07-11T15:11:27.910 に答える