【发布时间】:2014-12-07 16:20:54
【问题描述】:
我在这里问了一个类似的问题: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是一个字典数组。双打在其条目内。 -
澄清一下,
logsArray是一个字典数组,而不是代码中的双精度数组。那就是问题所在。你不能reduce一个字典数组。 -
好的,那么我如何从这些字典中创建一个双精度数组?或者这甚至是接近它的最佳方式?
-
您的核心数据结构如何?是否有与双打相关的各种键?如果是这样,那些键是什么?
-
是的,我有两个实体“totalWorkTimeInHours”,它是一个 NSTimeInterval(又名 Double),四舍五入到小数点后两位,然后存储在其键下。另一个是“dateString”,它只是将日期标签添加到我的表格视图中的 detailTextLabel。我将在 Core Data 中存储这些代码的位置添加代码。
标签: ios arrays core-data swift double