Search code examples
arrayscore-dataswift4nsmanagedobject

convert nsmanganedobject to array to find sum of array


My code below is trying to take core data from a NSManagedObject append it to an array. The core data element is saved as a string. My code is not compelling. Ideally the code should be able to append code into the array then the array is filled, find the sum of the numbers added together and print them into the viewDidLoad() func.

var itemName : [NSManagedObject] = []

       func performAction() {
        let appD = UIApplication.shared.delegate as! AppDelegate

        let context = appD.persistentContainer.viewContext

        let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Data")
        request.returnsObjectsAsFaults = false
        do {
            let result = try context.fetch(request)
            var retrievedData = [Double]()
            for data in result as! [NSManagedObject] {
                if let value = data.value(forKey: "ee") as? Double {
                    retrievedData.append(value)
                }
            }

            let arraySum = retrievedData.reduce(0, +)
            print(arraySum)

        } catch {

            print("Failed")
        }
    }

enter image description here


Solution

  • I reviewed your code when you will need to change small thing over there. Replace performAction function as per my updated answer.

     func performAction() {
            let appD = UIApplication.shared.delegate as! AppDelegate
    
            let context = appD.persistentContainer.viewContext
    
            let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Data")
            request.returnsObjectsAsFaults = false
            do {
                let result = try context.fetch(request)
                var retrievedData = [Double]()
                for data in result as! [NSManagedObject] {
                    if let value = data.value(forKey: "ee") as? String {
                        retrievedData.append(Double(value) ?? 0)
                    }
                }
    
                let arraySum = retrievedData.reduce(0, +)
                print(arraySum)
    
            } catch {
    
                print("Failed")
            }
        }