2016-11-03 7 views
0

私はGoogleとSEの両方で見てきましたが、私の質問に対する答えを見つけることができなかったので、単純な解決策を見落としてしまった場合は謝ります。私はまだ緑色なので、適切な検索用語を使用していない可能性があります。 :)KVCエラー集約プロパティを取得しています

さて、私は私がしたいと思うところに99%いるように感じます。私はaccounts関係にsumをやろうとしている、要するに

class func fetchGroupTotal(_ group: Int, for managedObjectContext: NSManagedObjectContext) -> Double { 
    let fetchRequest: NSFetchRequest<Group> = Group.fetchRequest() 
    let keyPathExpression = NSExpression(forKeyPath: "accounts.balance") 
    let sumExpression = NSExpression(forFunction: "sum:", arguments: [keyPathExpression]) 
    let expressionDescription = NSExpressionDescription() 
    expressionDescription.name = "groupSum" 
    expressionDescription.expression = sumExpression 
    expressionDescription.expressionResultType = .decimalAttributeType 
    fetchRequest.propertiesToFetch = [expressionDescription] 
    fetchRequest.resultType = .dictionaryResultType 

    do { 
     let results = try managedObjectContext.execute(fetchRequest) 
     print("\(results)") 
     return results.value(forKey: "groupSum") as! Double 
    } catch { 
     fatalError("Error fetching SUM: \(error)") 
    } 
} 

、その部分が動作しているようだ:私は、次のクラスの機能を持っています。私が定義したgroupSumプロパティにアクセスしようとすると、問題が発生します。次のエラーが表示されます。

Terminating app due to uncaught exception 'NSUnknownKeyException', reason: 
'[<NSAsynchronousFetchResult 0x600000288de0> valueForUndefinedKey:]: this class is not 
key value coding-compliant for the key groupSum.' 

結果からgroupSumを取得するにはどうすればよいですか?

答えて

0

Whew!それは1時間ほどだったが、多くのGoogle検索が失敗した後、ついにfound my answerが見つかりました。私がfetchRequestとどのように宣言したかを変更すると、私はプロパティに[NSDictionary]としてアクセスすることができました。興味があるかもしれない人のために

、ここに私の機能の最終バージョンです:

class func fetchTotal(_ group: Int, for managedObjectContext: NSManagedObjectContext) -> Double { 

    // Right here is where the magic happens: 
    let fetchRequest: NSFetchRequest<NSFetchRequestResult> = Group.fetchRequest() 

    let keyPathExpression = NSExpression(forKeyPath: "accounts.balance") 
    let sumExpression = NSExpression(forFunction: "sum:", arguments: [keyPathExpression]) 
    let expressionDescription = NSExpressionDescription() 
    expressionDescription.name = "groupSum" 
    expressionDescription.expression = sumExpression 
    expressionDescription.expressionResultType = .decimalAttributeType 
    fetchRequest.propertiesToFetch = [expressionDescription] 
    fetchRequest.resultType = .dictionaryResultType 
    fetchRequest.returnsDistinctResults = true 

    do { 
     let results = try managedObjectContext.fetch(fetchRequest).first 
     if let result = results as? NSDictionary { 
      return result.value(forKey: "groupSum") as! Double 
     } 
     return 0.00 
    } catch { 
     fatalError("Error fetching SUM: \(error)") 
    } 
} 
関連する問題