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

SOLVED: Swift: Nil Error when using self.moc.save() to save in core data

Forums > SwiftUI

I get nil error since I changed my project to use 'objectWillChange.send()'. Because I needed to update the view manually since it doesn't update itself for custom carousel view(because of core data?).

If I write "1" and tap the next button(NavigationLink)

Console log page.name: 1 catch error: nilError

Here is the codes.

AddPage Class

class AddPage: ObservableObject {
@Environment(\.presentationMode) var presentation
@Environment(\.managedObjectContext) var moc

func addPage(item: String) {

    if item != "" {

        let page = Page(context: self.moc)
        page.name = item

        do {
            print("page.name: \(page.name ?? "Unknown")")
            try self.moc.save()
        } catch {
        print("catch: \(error)")
        }

        objectWillChange.send()
        presentation.wrappedValue.dismiss()
    }
}
}

AddPageView

@ObservedObject var add = AddPage()  

NavigationLink(destination: ContentView()){
Text("Next")
    .background(
        Rectangle()
            .frame(width: 330, height: 60, alignment: .center)
    )
    .onTapGesture {
        add.addPage(item: pageName)
    }
}

SceneDelegate Class

added only

var addpage = AddPage()
let contentView = ContentView()
            .environment(\.managedObjectContext, context)
            .environmentObject(addpage)

Can someone please help me..?

2      

SwiftUI's environment is only available within a View so your moc will always be nil here.

2      

Thank you so much for your reply!! You saved my time so much!

2      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

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.