How to sum a double attribute from CoreData in swift

后端 未结 2 699
-上瘾入骨i
-上瘾入骨i 2021-01-07 13:57

I asked a similar question here: Getting the sum of an array of doubles in swift

but I still haven\'t gotten to a solution. Since the last question I changed my core

2条回答
  •  忘掉有多难
    2021-01-07 14:26

    In your current code, you're attempting to cast logsArray as an array of doubles when it's in fact an array of NSManagedObjects. That's why you're getting an error when you attempt to reduce the array.

    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)")
    }
    

提交回复
热议问题