从Coredata Swift运行总和

时间:2015-11-28 23:08:59

标签: ios swift core-data

我正在尝试在Coredata中获得小于或等于所评估日期的所有事务的运行总和。我可以获得给定日期内所有交易的总数,但我还没弄清楚如何获得交易的运行总额,包括评估日期。这是我的代码:

var _fetchedData: [[String : AnyObject]]? = nil
var fetchedData:[[String : AnyObject]]? {


    if _fetchedData != nil {
        return _fetchedData
    }

    print("====== fetchedData Initialization ======")

    let fetchRequest = NSFetchRequest()
    // Edit the entity name as appropriate.
    let entity = NSEntityDescription.entityForName("Transaction", inManagedObjectContext: managedObjectContext)
    fetchRequest.entity = entity


    // Pull sum of transactions
    let expression=NSExpressionDescription()
    expression.expression=NSExpression(format: "sum:(splits.amount)")
    expression.name="Sum"
    expression.expressionResultType=NSAttributeType.DoubleAttributeType



    // Pull running sum of transactions
    let subqueryExpression=NSExpressionDescription()
    let sqExpression=NSExpression(format: "SUBQUERY(splits, $t, date<$t.date)")
    subqueryExpression.expression=NSExpression(forFunction: "sum", arguments: [sqExpression])
    subqueryExpression.expressionResultType=NSAttributeType.DoubleAttributeType
    subqueryExpression.name="RunningSum"

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

    // Sets up query details
    fetchRequest.propertiesToFetch=["date",expression]
    fetchRequest.propertiesToGroupBy=["date"]
    fetchRequest.resultType = NSFetchRequestResultType.DictionaryResultType


    let sortDescriptor1 = NSSortDescriptor(key: "date", ascending: false)
    let sortDescriptors = [sortDescriptor1]

    fetchRequest.sortDescriptors = sortDescriptors

    var results:[[String : AnyObject]]=[]

    do {
        results = try self.managedObjectContext.executeFetchRequest(fetchRequest) as! [[String : AnyObject]]
        print("results=\(results)")
        for result in results {


            var filteredResults:[[String:AnyObject]] = results.filter({
                ($0["date"] as! NSDate).compare(result["date"] as! NSDate) == NSComparisonResult.OrderedAscending

            })

            //                let runningTotal=filteredResults.reduce(0) { ($0["Sum"] as! NSNumber) + ($1["Sum"] as! NSNumber)}
            print("runningTotal=\(filteredResults) result=\(result)")

        }


    } catch let error as NSError {
        print("error=\(error)")
    } catch {
        print("catch")
    }

    _fetchedData=results

    return _fetchedData

}

运行总和表达式无法编译,我收到一条错误消息:

  

由于未捕获的异常而终止应用   'NSInternalInconsistencyException',原因:'sum不支持   方法“。

有人可以帮我弄清楚如何计算获取请求中评估日期的运行总和吗?

0 个答案:

没有答案