将 nsmanganedobject 转换为数组以查找数组的总和

convert nsmanganedobject to array to find sum of array

我下面的代码试图从 NSManagedObject 中获取核心数据并将其附加到数组中。核心数据元素保存为字符串。我的代码没有说服力。理想情况下,代码应该能够将代码附加到数组中,然后填充数组,找到加在一起的数字之和并将它们打印到 viewDidLoad() 函数中。

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

当您需要更改那边的小东西时,我检查了您的代码。根据我更新的答案替换 performAction 函数。

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