如何汇总核心数据

时间:2019-06-24 15:01:55

标签: core-data nsdictionary nsfetchrequest

我有一个像这样的数据模型:enter image description here

我想按catalog.item,money.year,money.month分组获取汇总列表,并且我尝试了几种可以在Internet上找到的方法,但是失败了。
< / p>

我尝试了“让fetchRequest = NSFetchRequest(entityName:“ CashFlow”)“”
和“让fetchRequest = NSFetchRequest (entityName:” CashFlow“)”

总是相同的错误:fetchRequest的打印说明: 表达式产生的错误:错误:/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)")
    }

1 个答案:

答案 0 :(得分:0)

无论它如何工作:

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