如何在swift中对CoreData中的double属性求和 [英] How to sum a double attribute from CoreData in swift
问题描述
我在这里问了一个类似的问题:获取swift中双精度数组的总和
I asked a similar question here: Getting the sum of an array of doubles in swift
但我仍然没有得到解决方案。自上一个问题以来,我将核心数据属性类型更改为double。问题是这个。如何获得存储在核心数据中的所有双打的总和?
but I still haven't gotten to a solution. Since the last question I changed my core data attribute type to double. The question is this. How to I get a sum of all those doubles stored in core data?
现在我有:
// Get CoreData
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let managedContext : NSManagedObjectContext = appDelegate.managedObjectContext!
var fetchRequest = NSFetchRequest(entityName: "Log")
fetchRequest.returnsObjectsAsFaults = false;
var results: NSArray = managedContext.executeFetchRequest(fetchRequest, error: nil)!
//attempt to type cast a logs array
var logs = managedContext.executeFetchRequest(fetchRequest, error: nil)!
var logsArray = logs as NSArray as [Double]
var totalHoursWorkedSum = logsArray.reduce(0, combine: +)
//this builds, but crashes the app with 'EXC_BAD_INSTRUCTION' when I try to set a label.text with 'totalHoursWorkedSum'
我真的不确定还有什么可以尝试所以我对可能实现同一目标的任何不同方法持开放态度。
I'm really not sure what else to try so I'm open to any different approaches that may accomplish the same goal.
以下是我获取和存储原始值的方法:
Here's how I get and store the original values:
//Time logging
var punchInTime : NSDate = punchTimes.objectForKey("punchInTime") as NSDate
var punchOutTime = NSDate()
var totalWorkTime = NSDate().timeIntervalSinceDate(punchInTime)
//"punchInTime" is stored in NSUserDefaults
var totalWorkTimeInHoursNotRounded = (totalWorkTime/60/60)
var totalWorkTimeInHours = Double(round(1000*totalWorkTimeInHoursNotRounded)/1000)
//the rounded form of the above
//format a date
var dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .FullStyle
//Save to CoreData
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let managedContext : NSManagedObjectContext = appDelegate.managedObjectContext!
let entity = NSEntityDescription.entityForName("Log", inManagedObjectContext: managedContext)
var newLog = DataModel(entity: entity!, insertIntoManagedObjectContext: managedContext)
newLog.totalWorkTimeInHours = totalWorkTimeInHours
newLog.dateString = dateFormatter.stringFromDate(NSDate())
managedContext.save(nil)
punchTimes.objectForKey("punchInTime") == nil
推荐答案
在您当前的代码中,您正在尝试投射 logsArray
作为一个双精度数组,当它实际上是一个 NSManagedObject
的数组时。这就是为什么当你尝试 reduce
数组时出现错误的原因。
In your current code, you're attempting to cast logsArray
as an array of doubles when it's in fact an array of NSManagedObject
s. That's why you're getting an error when you attempt to reduce
the array.
获取总和与Core Data中的totalWorkTimeInHours键相关联的double值,您必须从获取请求返回的每个 NSManagedObject
中访问totalWorkTimeInHours键,然后将它们添加到一起,例如:
To get the sum of the double values associated with your "totalWorkTimeInHours" key in Core Data, you have to access the "totalWorkTimeInHours" key from each NSManagedObject
returned from your fetch request then add them together, ex:
override func viewDidLoad() {
super.viewDidLoad()
//CoreData
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let managedContext : NSManagedObjectContext = appDelegate.managedObjectContext!
var fetchRequest = NSFetchRequest(entityName: "Log")
fetchRequest.returnsObjectsAsFaults = false;
var results: NSArray = managedContext.executeFetchRequest(fetchRequest, error: nil)!
var totalHoursWorkedSum: Double = 0
for res in results {
var totalWorkTimeInHours = res.valueForKey("totalWorkTimeInHours") as Double
totalHoursWorkedSum += totalWorkTimeInHours
}
print("Sum = \(totalHoursWorkedSum)")
}
这篇关于如何在swift中对CoreData中的double属性求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!