简体   繁体   中英

I want to save to CORE DATA, but I keep getting a 'An NSManagedObject of class 'Reminder' must have a valid NSEntityDescription.'

What am I doing wrong?

This is what I want to save:

//To save in Core Data
let my_reminder = Reminder(context: CoreDataService.context)
my_reminder.name = "a title"
my_reminder.date = "a date"
my_reminder.content = "some text"
CoreDataService.saveContext() //a class that handles core data

This is my CoreDataService Class:

import Foundation
import CoreData

class CoreDataService {

    static var context: NSManagedObjectContext {
        return persistentContainer.viewContext
    }

    private init(){}

    // MARK: - Core Data stack
    static var persistentContainer: NSPersistentContainer = {
        let container = NSPersistentContainer(name: "project_name")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()

    // MARK: - Core Data Saving support
    static 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)")
            }
        }
    }

}

Error message:

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

I Keep getting the error time and time again, do I need to update the plist ? I Checked everything and still nothing seems to work

(I'm using Swift 4 and XCODE 9 by the way).

Sorry I can't remember the username, but somebody recomended I changed line:

let my_reminder = Reminder(context: CoreDataService.context)

to something like:

if let my_reminder = NSEntityDescription.insertNewObject(forEntityName: "Reminder", into: CoreDataService.context) as? Reminder {
            print("Start saving")
            my_reminder.name = "a title"
            my_reminder.date = "a date"
            my_reminder.content = "some text"
            CoreDataService.saveContext()
        }

also, I had something wrong in my CoreDataService class, the NSPersistentContainer doesn't recieve the name of the of the project, but rather the name of the XCDataModeld file, which tends to be the same, but wasn't in my case:

let container = NSPersistentContainer(name: "Model")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM