总结从CoreData的双重属性,我在这里问类似的问题:Getting the sum of an array of doubles in swift如何迅速
,但我仍然没有得到一个解决方案。自从上一个问题以来,我将我的核心数据属性类型改为了两倍。问题是这个。如何获得存储在核心数据中的所有这些双打的总和?
现在我有:
// 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'
我真的不知道还有什么尝试,所以我开到了可以完成同样的目标,任何不同的做法。
下面是如何获取和存储原始值:
//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'是一个字典数组。双打是在其条目。 – 2014-12-07 16:29:37
为了说明,'logsArray'是一个字典数组,不像你在代码中那样是一个双精度数组。那就是问题所在。你不能“减少”一系列字典。 – 2014-12-07 16:44:42
好的,那么我如何从这些字典中创建一个双打数组?或者甚至是接近它的最好方式? – Leighton 2014-12-07 17:48:35