Data Persistence using Core Data

So I created a program without selecting “use core data” and realized after trying to make a persistence data storage that it helps very much so I created a new program and selected it this time and copied everything over. It provided a file called “Persistence” and the contentView file had a bunch of stuff already filled in (Also something called the title of the program). I have the data I need saved to the persistent data storage narrowed down to a singular array, but none of the videos I found online showed this version of xcode that supplied a “Persistence” file when using core data so I’m unsure how to use it. I will provide the contentView and Persistence file for context. The array I need saved is called mainList in contentView.

ContentView:

import SwiftUI

import CoreData



struct ContentView: View {

    var mainList = [RecipeList(),RecipeList(),RecipeList(),RecipeList(),RecipeList()]

    

    @Environment(\.managedObjectContext) private var viewContext



    @FetchRequest(

        sortDescriptors: [NSSortDescriptor(keyPath: \Item.timestamp, ascending: true)],

        animation: .default)

    private var items: FetchedResults<Item>



    var body: some View {

        NavigationView {

            List {

                ForEach(items) { item in

                    NavigationLink {

                        Text("Item at \(item.timestamp!, formatter: itemFormatter)")

                    } label: {

                        Text(item.timestamp!, formatter: itemFormatter)

                    }

                }

                .onDelete(perform: deleteItems)

            }

            .toolbar {

                ToolbarItem(placement: .navigationBarTrailing) {

                    EditButton()

                }

                ToolbarItem {

                    Button(action: addItem) {

                        Label("Add Item", systemImage: "plus")

                    }

                }

            }

            Text("Select an item")

        }

    }



    private func addItem() {

        withAnimation {

            let newItem = Item(context: viewContext)

            newItem.timestamp = Date()



            do {

                try viewContext.save()

            } catch {

                // Replace this implementation with code to handle the error appropriately.

                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

                let nsError = error as NSError

                fatalError("Unresolved error \(nsError), \(nsError.userInfo)")

            }

        }

    }



    private func deleteItems(offsets: IndexSet) {

        withAnimation {

            offsets.map { items[$0] }.forEach(viewContext.delete)



            do {

                try viewContext.save()

            } catch {

                // Replace this implementation with code to handle the error appropriately.

                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

                let nsError = error as NSError

                fatalError("Unresolved error \(nsError), \(nsError.userInfo)")

            }

        }

    }

}



private let itemFormatter: DateFormatter = {

    let formatter = DateFormatter()

    formatter.dateStyle = .short

    formatter.timeStyle = .medium

    return formatter

}()



struct ContentView_Previews: PreviewProvider {

    static var previews: some View {

        ContentView().environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)

    }

}

Persistence:

import CoreData



struct PersistenceController {

    static let shared = PersistenceController()



    static var preview: PersistenceController = {

        let result = PersistenceController(inMemory: true)

        let viewContext = result.container.viewContext

        for _ in 0..<10 {

            let newItem = Item(context: viewContext)

            newItem.timestamp = Date()

        }

        do {

            try viewContext.save()

        } catch {

            // Replace this implementation with code to handle the error appropriately.

            // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

            let nsError = error as NSError

            fatalError("Unresolved error \(nsError), \(nsError.userInfo)")

        }

        return result

    }()



    let container: NSPersistentCloudKitContainer



    init(inMemory: Bool = false) {

        container = NSPersistentCloudKitContainer(name: "ReciStorage")

        if inMemory {

            container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")

        }

        container.loadPersistentStores(completionHandler: { (storeDescription, error) in

            if let error = error as NSError? {

                // Replace this implementation with code to handle the error appropriately.

                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.



                /*

                 Typical reasons for an error here include:

                 * The parent directory does not exist, cannot be created, or disallows writing.

                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.

                 * The device is out of space.

                 * The store could not be migrated to the current model version.

                 Check the error message to determine what the actual problem was.

                 */

                fatalError("Unresolved error \(error), \(error.userInfo)")

            }

        })

        container.viewContext.automaticallyMergesChangesFromParent = true

    }

}

Image showing the thing named the title of the program that I’m certain is relevant to the persisting data storage:

Also I’m unsure what I need to replace those comments with and what subclasses I should add to existing swift files like “codable” for example.

Any help would be greatly appreciated.

Answered by WeagleWeagle in 715616022

https://youtu.be/nalfX8yP0wc

An explanation of core data given by Xcode

Accepted Answer

https://youtu.be/nalfX8yP0wc

An explanation of core data given by Xcode

Also see https://youtu.be/tww2vbJjXpA for CloudKit (sharing data between the user's devices)

Data Persistence using Core Data
 
 
Q