總結從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