如何在核心数据中求和

How to Sum in Core Data

我有这样的数据模型:

我想按 catalog.item、money.year、money.month 分组获取总和列表,我尝试通过互联网上的几种方法来实现,但是我失败了。

我试过 "let fetchRequest = NSFetchRequest(entityName:"CashFlow")"
和 "let fetchRequest = NSFetchRequest< CashFlow >(entityName:"CashFlow")"

fetchRequest 的描述总是一样的error:Printing: 表达式产生错误:错误:/var/folders/8j/g0yb8vwx23z2s1qykxz2q7hh0000gn/T/expr51-6487f6..swift:1:65:错误:使用未声明的类型'CoreData' Swift._DebuggerSupport.stringForPrintObject(Swift.UnsafePointer>(bitPattern: 0x127497460)!.pointee)

class MonthlySum  {
public var year:Int16 = 0
public var month:Int16 = 0
public var emoji:String = ""
public var item:String = ""
public var budget:Int16 = 0
public var total:Int16 = 0
}

//我也试过将MonthlySum定义为NSManagedObject

    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName:"CashFlow")

    // Set the batch size to a suitable number.
    //fetchRequest.fetchBatchSize = 32

    fetchRequest.predicate = NSPredicate(format: "money.year = %d and money.month = %d",year,month)

    // sort by day
    fetchRequest.sortDescriptors = [NSSortDescriptor(key: "money.cata.item", ascending: true)]

    //group by day for sum
    //fetchRequest.propertiesToGroupBy = ["money.cata.emoji","money.cata.item","money.budget"]
    var expressionDescriptions = [AnyObject]()
    var expD = NSExpressionDescription()

    // select year
    expD.name = "year"
    expD.expression = NSExpression(forKeyPath: "money.year")
    expD.expressionResultType = .integer16AttributeType

    expressionDescriptions.append(expD)

    // select month
    expD.name = "month"
    expD.expression = NSExpression(forKeyPath: "money.month")
    expD.expressionResultType = .integer16AttributeType

    expressionDescriptions.append(expD)

    // select category item
    expD.name = "item"
    expD.expression = NSExpression(forKeyPath: "money.cata.item")
    expD.expressionResultType = .stringAttributeType

    expressionDescriptions.append(expD)

    // select category emoji
    expD.name = "emoji"
    expD.expression = NSExpression(forKeyPath: "money.cata.emoji")
    expD.expressionResultType = .stringAttributeType

    expressionDescriptions.append(expD)

    // select month
    expD.name = "budget"
    expD.expression = NSExpression(forKeyPath: "money.budget")
    expD.expressionResultType = .integer16AttributeType

    expressionDescriptions.append(expD)

    //select @sum.amount as dailysum
    expD = NSExpressionDescription()
    expD.name = "total"
    expD.expression = NSExpression(forFunction: "sum:", arguments: [NSExpression(forKeyPath: "amount")])
    expD.expressionResultType = .integer16AttributeType

    expressionDescriptions.append(expD)

    fetchRequest.propertiesToFetch = expressionDescriptions
    fetchRequest.resultType = .dictionaryResultType

    var result = [MonthlySum]()
    let m = MonthlySum()
    do {
        let fetchResult = try viewContext.fetch(fetchRequest) as! [MonthlySum]
        /*
        for item in fetchResult {
            m.budget = item.value(forKey: "budget") as! Int16
            m.emoji = item.value(forKey: "emoji") as! String
            m.item = item.value(forKey: "item") as! String
            m.month = item.value(forKey: "month") as! Int16
            m.total = item.value(forKey: "total") as! Int16
            m.year = item.value(forKey: "year") as! Int16
            result.append(m)
        } */
    } catch {
        let nserror = error as NSError
        fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
    }

不管它是这样工作的:

let fetchRequest = NSFetchRequest<NSDictionary>(entityName:"Trade")

    fetchRequest.predicate = NSPredicate(format: "year = %d and month = %d",year,month)

    // sort by day
    fetchRequest.sortDescriptors = [NSSortDescriptor(key: "day", ascending: true)]

    //group by day for sum
    fetchRequest.propertiesToGroupBy = ["day"]
    var expressionDescriptions = [AnyObject]()
    var expD = NSExpressionDescription()

    // select day
    expD.name = "day"
    expD.expression = NSExpression(forKeyPath: "day")
    expD.expressionResultType = .integer16AttributeType

    expressionDescriptions.append(expD)

    //select @sum.amount as dailysum
    expD = NSExpressionDescription()
    expD.name = "total"
    expD.expression = NSExpression(forFunction: "sum:", arguments: [NSExpression(forKeyPath: "amount")])
    expD.expressionResultType = .integer16AttributeType

    expressionDescriptions.append(expD)

    fetchRequest.propertiesToFetch = expressionDescriptions
    fetchRequest.resultType = .dictionaryResultType

    var result = [Int:String]()

    do {
        let fetchResult = try viewContext.fetch(fetchRequest)
        for item in fetchResult {
            result[item.value(forKey: "day") as! Int] = String(describing: item.value(forKey: "total") as! Int)}
    } catch {
        let nserror = error as NSError
        fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
    }

    return result