2013-02-11 4 views
5

コアデータを使用しているときに問題が発生しました。私は属性 "量"を持つ実体 "運動"を持っています。すべてのインスタンスの「金額」の合計をどのようにして作成しますか?私はNSExpressionDescriptionの使い方を理解したいと思いますが、十分にNSSetです。コアデータすべてのインスタンス属性の合計

答えて

20

フェッチするリクエストのプロパティを設定します。

fetchRequest.propertiesToFetch = @[expressionDescription]; 

また、必要に応じて述語を設定することもできます。

最後に、要求を実行して1つのキー(@ "sumOfAmounts")を持つ辞書を含む配列を取得し、その値は合計量のNSNumberです。ここで

NSError *error = nil; 
NSArray *result = [managedObjectContext executeFetchRequest:fetchRequest error:&error]; 
if (result == nil) 
{ 
    NSLog(@"Error: %@", error); 
} 
else 
{ 
    NSNumber *sumOfAmounts = [[result objectAtIndex:0] objectForKey:@"sumOfAmounts"]; 
} 

乾杯

+1

なぜdownvote? – e1985

+0

申し訳ありませんが、これは私の悪いです、私はupvoteしたい... Plz私の投票を切り替えることができるようにあなたのポストで少し編集を提供する – Yaman

+0

ありがとう男!うまくいく! – Vins

2

最良の方法は、fetch for specific valuesを使用して、あなたがキー値式の結果である表現の記述とが一致した辞書を含む1つの要素の配列を取得しますフェッチを実行するとNSExpressionDescription with a sum: function.

を供給することです。この場合、sumキーが得られます。このキーの値は、式が与えられた属性の合計になります。

NSManagedObjectContext *managedObjectContext = ... 

私たちは、戻り値の型辞書でフェッチ要求を作成します:

NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:NSStringFromClass([Movement class])]; 
fetchRequest.resultType = NSDictionaryResultType; 

その後、我々は、合計を計算するための式の説明を作成します。

NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init]; 
expressionDescription.name = @"sumOfAmounts"; 
expressionDescription.expression = [NSExpression expressionForKeyPath:@"@sum.amount"]; 
expressionDescription.expressionResultType = NSDecimalAttributeType; 

をmanagedObjectContextを持つ

1

NSExpressionNSExpressionDescriptionを使用して管理対象オブジェクトの属性を合計するスウィフト例です。この例では、管理オブジェクトの名前はMovementであり、合計の属性はamountであると仮定しています。

例:階段の

func sumAmount -> Double { 

    var amountTotal : Double = 0 

    // Step 1: 
    // - Create the summing expression on the amount attribute. 
    // - Name the expression result as 'amountTotal'. 
    // - Assign the expression result data type as a Double. 

    let expression = NSExpressionDescription() 
    expression.expression = NSExpression(forFunction: "sum:", arguments:[NSExpression(forKeyPath: "amount")]) 
    expression.name = "amountTotal"; 
    expression.expressionResultType = NSAttributeType.DoubleAttributeType 

    // Step 2: 
    // - Create the fetch request for the Movement entity. 
    // - Indicate that the fetched properties are those that were 
    // described in `expression`. 
    // - Indicate that the result type is a dictionary. 

    let fetchRequest = NSFetchRequest(entityName: "Movement") 
    fetchRequest.propertiesToFetch = [expression] 
    fetchRequest.resultType = NSAttributeType.DictionaryResultType 

    // Step 3: 
    // - Execute the fetch request which returns an array. 
    // - There will only be one result. Get the first array 
    // element and assign to 'resultMap'. 
    // - The summed amount value is in the dictionary as 
    // 'amountTotal'. This will be summed value. 

    do { 
     let results = try context.executeFetchRequest(fetchRequest) 
     let resultMap = results[0] as! [String:Double] 
     amountTotal = resultMap["amountTotal"]! 
    } catch let error as NSError { 
     NSLog("Error when summing amounts: \(error.localizedDescription)") 
    } 

    return amountTotal 
} 

追加ディスカッション:

ステップ1 - NSExpressionDescription変数を作成します。このNSExpressionDescriptionは、どのタイプの関数が引数に適用されるかを示します。 の合計機能が属性に適用されています。

expression.expression = NSExpression(forFunction: "sum:", 
    arguments:[NSExpression(forKeyPath: "amount")]) 

引数パラメータは配列であることに注意してください。配列にはさまざまな種類の式を渡すことができますが、この場合はamount属性のみが必要です。

ステップ2 - ここでフェッチ要求が確立されます。結果の型が辞書として指定されていることに注意してください:fetchRequest.resultType = NSAttributeType.DictionaryResultType。ステップ3ではという値をexpression.nameというキーを使用して合計値にアクセスします。

ステップ3 - フェッチ要求を実行し、返された要素は1つの要素配列になります。要素は、[String:Double]let resultMap = results[0] as! [String:Double]にカーストする辞書になります。辞書の値はDoubleです。ステップ1ではexpression.expressionResultTypeがDoubleになるためです。

は最後に、我々はamountTotalキーに関連付けられた辞書値を呼び出すことにより、合計アクセス:resultMap["amountTotal"]!


参考文献:

NSExpressionNSExpressionDescription

関連する問題