UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Is this correct way to use CoreData with the swiftUI 2.0 @main app protocol?

Forums > SwiftUI

Is this the correct way to to use coredata with the new App protocol? My app works like this but im a beginner so dont know if this is making some bad performance or if the app will crash in future when the coredata model get more entrys?

See down: ContentView is the navigation menu, and the views i navigate to from contentview can use the coredata through the @Environment of managedObjectContext now so it seems like all is working..

import SwiftUI
import CoreData
@main
struct TestApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
                .environment(\.managedObjectContext, persistentContainer.viewContext)

        }
    }
    var persistentContainer: NSPersistentContainer = {
                let container = NSPersistentContainer(name: "TestApp")
                container.loadPersistentStores(completionHandler: { (storeDescription, error) in
                    if let error = error as NSError? {
                        fatalError("Unresolved error \(error), \(error.userInfo)")
                    }
                })
                return container
            }()
            func saveContext() {
                let context = persistentContainer.viewContext
                if context.hasChanges {
                    do {
                        try context.save()
                    } catch {
                        let nserror = error as NSError
                        fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
                    }
                }
            }
}

4      

I have the same question. Similarly would like to know where to put Scene Delegate code that deals with configuring core data like:

context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy 
context.automaticallyMergesChangesFromParent = true 

4      

You might want to add an .onDismiss(perform: saveContext) after the .environment line on the ContentView()

3      

I'm on a similar journey today with learning Core Data and the new SwiftUI Life Cycle. A few things I've found helpful:

  • Apple included some template code in the latest version of Xcode. They put most of the Core Data code in a seperate Persistence.swift file.
  • This thread suggests putting Scene change code in App file: https://developer.apple.com/forums/thread/650876

3      

If you wonder where to put the line:
container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy

open the Persistence.swift file (new in Swift 2) and add it in the init() like:

init(inMemory: Bool = false) {
        container = NSPersistentContainer(name: "NewCoreDataProject")
        container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy 
    [...]

https://www.hackingwithswift.com/forums/swiftui/is-this-correct-way-to-use-coredata-with-the-swiftui-2-0-atmain-app-protocol/2521/2522

7      

Great topic. I'm learning app programming using swift and hackingwithswift has been great. I placed the mergepolicy as @multitudes suggested addapting the template and I don't get the needed behavior. The one side field gets repeated still using the following code to build the list.

              List {
                    ForEach(pumpBrands, id: \.self) { brand in
                        Section(header: Text(brand.wrappedBrandName)) {
                            ForEach(brand.modelArray, id: \.self) { model in
                                HStack {
                                Text(model.wrappedModelNumber)
                                Text(model.modelDescription ?? "")
                                }
                            }
                        }
                    }
                }

I inserted the merge policy like this.


    init(inMemory: Bool = false) {
        container = NSPersistentContainer(name: "CoreDataPractice2012")
        container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
        container.viewContext.automaticallyMergesChangesFromParent = true  

        //.... 

Any tips much appreciated. 

3      

Resolved...I found my issue above. I had forgotten to place (or thought I had already placed) an attribute contraint for for the entity.

3      

@Hamztr

to the gent at the very start, you are missing a perenthesis after your .environment line; question from me regarding the trump merge policy, where is best to put it in this stack? the examples above use the boilerplate that comes by checking the include core data checkbox. I prefer to do things programaticaly, i dont know why i do, it makes life much much harder!

import SwiftUI
import CoreData
@main
struct ExampleAppName: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
                .environment(\.managedObjectContext, pC.viewContext)
        }
    }
}
    var pC: NSPersistentContainer = {
        let container = NSPersistentContainer(name: "ExampleDataModelName")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()
    func saveContext() {
        let context = pC.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
        }
    }
}

3      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.