TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Project 12, part 1 An NSManagedObject of class 'Wizard' must have a valid NSEntityDescription.

Forums > 100 Days of SwiftUI

Hello,

In the last part of Project 12, part 1 I have this kind of erro when i try to ad the name of the wizard.

An NSManagedObject of class 'Wizard' must have a valid NSEntityDescription.

some one can help me to resolve it?

Thanks

3      

Might be that there's something wrong initialising the NSPersistentContainer, most commonly with the incorrect name. It should have the same name as the file with the extension .xcdatamodeld. in your project.

Check that first ...

4      

Have you created your NSManagedObject subclasses via Xcode? From my understanding in this chapter you don't rely on code generation from Xcode but you have to create your own classes?

https://www.hackingwithswift.com/books/ios-swiftui/creating-nsmanagedobject-subclasses

3      

Hacking with Swift is sponsored by String Catalog.

SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!

Localize My App

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

yes I have done!

import Foundation
import CoreData

class DataController: ObservableObject {

    let container = NSPersistentContainer(name: "CoreDataProject")

    init() {
        container.loadPersistentStores { description, error in
            if let error = error {
                print("Core Data failed to load: \(error.localizedDescription)")
                return
            }

            self.container.viewContext.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump
        }
    }

}

3      

import Foundation
import CoreData

@objc(Movie)
public class Movie: NSManagedObject {

}

I think this i s teh correct subcalss

3      

When you want to add a Wizard you need a class Wizard, not Movie. That's what the error message is saying.

3      

I have redone the procedure for but the error is the same!

import Foundation
import CoreData

@objc(Wizard)
public class Wizard: NSManagedObject {

}
import Foundation
import CoreData

extension Wizard {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Wizard> {
        return NSFetchRequest<Wizard>(entityName: "Wizard")
    }

    @NSManaged public var name: String?

    public var wrappedName: String {
        name ?? "Unknown Title"
    }

}

extension Wizard : Identifiable {

}

3      

In your data model for Core Data is an option which is called Code Generation. Is it set to manual?

Additionally, clean your build folder in Xcode. There is an option in the menu. I don't know the keyboard shortcut.

3      

I find The error.

I forgot to put thi in the main file of swift

let container = NSPersistentContainer(name: "CoreDataProject")

and

self.container.viewContext.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump

Thankyou for your Help!

4      

@ddko  

hey there, i had been trying, but what does "in the main file of swift" mean ? do you mean by DataController.swift ?

3      

@ddko  

Update! XCode 14.2

if you were like me consistently facing the same issue and tried out stack overflow method and failed here is update to please check out this solution from Paul https://www.hackingwithswift.com/quick-start/swiftui/how-to-configure-core-data-to-work-with-swiftui

Took me 2 days to find out the solution!

change "Main" to your "FileName" of .xcdatamodeld

and also please add back the

self.container.viewContext.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump

Here below is all the code inside PersistenceController.swift


import Foundation
import CoreData

struct PersistenceController {
    // A singleton for our entire app to use
    static let shared = PersistenceController()

    // Storage for Core Data
    let container: NSPersistentContainer

    // A test configuration for SwiftUI previews
    static var preview: PersistenceController = {
        let controller = PersistenceController(inMemory: true)

        // Create 10 example programming languages.
        for _ in 0..<10 {
            let wizard = Wizard(context: controller.container.viewContext)
            wizard.name = "Example wizard 1"
        }

        return controller
    }()

    // An initializer to load Core Data, optionally able
    // to use an in-memory store.
    init(inMemory: Bool = false) {
        // If you didn't name your model Main you'll need
        // to change this name below.
        container = NSPersistentContainer(name: "CoreDataProject")

        if inMemory {
            container.persistentStoreDescriptions.first?.url = URL(fileURLWithPath: "/dev/null")
        }

        container.loadPersistentStores { description, error in
            if let error = error {
                fatalError("Error: \(error.localizedDescription)")
            }
        }
        self.container.viewContext.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump
    }
    func save() {
        let context = container.viewContext

        if context.hasChanges {
            do {
                try context.save()
            } catch {
                // Show some error here
            }
        }
    }
}

then YourProjectApp


import SwiftUI
import CoreData

@main
struct CoreDataProjectApp: App {
    @Environment(\.scenePhase) var scenePhase

    let persistenceController = PersistenceController.shared

    var body: some Scene {
        WindowGroup {
            ContentView()
                .environment(\.managedObjectContext, persistenceController.container.viewContext)
        }
        .onChange(of: scenePhase) { _ in
            persistenceController.save()
        }
    }
}

3      

I had this same problem but neither of the comments above helped.

The solution for me was to update the CoreDataProjectApp.swift file and add

@StateObject private var dataController = DataContoller()

into the CoreDataProjectApp struct and give ContentView the modifier

.environment(\.managedObjectContext, dataController.container.viewContext)

3      

Hacking with Swift is sponsored by String Catalog.

SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!

Localize My App

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

Reply to this topic…

You need to create an account or log in to reply.

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.