2 Replies
      Latest reply on Jun 16, 2019 7:18 AM by wlionel
      wlionel Level 1 Level 1 (0 points)

        import UIKit

        import CoreData

        //import Foundation

        // @objc(Decisions)

         

        class ViewController: UIViewController, UITableViewDelegate, UIApplicationDelegate {

                init(){

            }

         

            required init?(coder aDecoder: NSCoder) {

                fatalError("init(coder:) has not been implemented")

            }

         

            var decisions = [String]()

         

           // var Gains: (() -> Void)!

         

         

                var gain1 = ""

                var gain2 = ""

                var gain3 = ""

                var gain4 = ""

         

         

            let Gains = [gain1, gain2, gain3, gain4] ["cannot use instance member within property initializer". Without this line the "forEach" doesn't work.

         

            override func viewDidLoad() {

                super.viewDidLoad()

           

            

                let persistentContainer = NSPersistentContainer(name: "No_Regrets")

                persistentContainer.loadPersistentStores { (_, error) in

                    if let error = error {

                        fatalError("Failed to load Core Data stack: \(error)")

                    }

                }

           

                // Creates a task with a new background context created on the fly

                persistentContainer.performBackgroundTask { (context) in

                    // Iterates the array

                    Gains.forEach { name in

                        // Creates a new entry inside the context `context` and assign the array element `name` to the dog's name

                        let gain1 = Gains(context: context)

                        gain1.name = name

                        let gain2 = Gains(context: context)

                        gain2.name = name

                        let gain3 = Gains(context: context)

                        gain3.name = name

                        let gain4 = Gains(context: context)

                        gain4.name = name

                    }

                    do {

                        // Saves the entries created in the `forEach`

                        try context.save()

                    } catch {

                        fatalError("Failure to save context: \(error)")

                    }

                }