Core Data NSManagedObject doesn't have a valid

2020-08-07 02:56发布

问题:

I am trying to set up core data with my Xcode project and running into an error that I can't seem to get rid of. I have an entity called UserDetails inside of StudyHub.xcdatamodeld. My code in the AppDelegate:

// MARK: - Core Data stack

lazy var persistentContainer: NSPersistentContainer = {
    /*
     The persistent container for the application. This implementation
     creates and returns a container, having loaded the store for the
     application to it. This property is optional since there are legitimate
     error conditions that could cause the creation of the store to fail.
     */
    let container = NSPersistentContainer(name: "DELETE")
    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)")
        }
    })
    return container
}()

// MARK: - Core Data Saving support

func saveContext () {
    let context = persistentContainer.viewContext
    if context.hasChanges {
        do {
            try context.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)")
        }
    }
}

// MARK: Send Data to CoreData

func saveUserDetails(data: [String: String]) {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext
    let user = UserDetails(context: context)
    if let authenticatedWith = data["authenticatedWith"] {
        user.authenticatedWith = authenticatedWith
    }
    if let email = data["email"] {
        user.email = email
    }
    if let fullName = data["fullName"] {
        user.fullName = fullName
    }
    if let username = data["username"] {
        user.username = username
    }
    if let schoolName = data["schoolName"] {
        user.schoolName = schoolName
    }
    if let schoolUID = data["schoolUID"] {
        user.schoolUID = schoolUID
    }
    if let facebookLink = data["facebookLink"] {
        user.facebookLink = facebookLink
    }
    if let twitterLink = data["twitterLink"] {
        user.twitterLink = twitterLink
    }
    if let instagramLink = data["instagramLink"] {
        user.instagramLink = instagramLink
    }
    if let vscoLink = data["vscoLink"] {
        user.vscoLink = vscoLink
    }
    appDelegate.saveContext()
}

My code for retrieving the data stored inside of a ViewController:

let user = UserDetails()

if (user.username != "") {
    self.navigationItem.title = user.username
} else {
    self.navigationItem.title = "Account."
}
self.usersNameLabel.text = user.fullName
if (user.schoolName != "") {
    self.usersSchoolNameLabel.setTitle(user.schoolName, for: .normal)
    self.usersSchoolNameLabel.isHidden = false
} else {
    self.addSchoolButton.isHidden = false
}
self.checkSocialLink(link: user.facebookLink!, button: self.facebookLinkButton) // TODO: Force unwrap might not work
self.checkSocialLink(link: user.twitterLink!, button: self.twitterLinkButton)
self.checkSocialLink(link: user.instagramLink!, button: self.instagramLinkButton)
self.checkSocialLink(link: user.vscoLink!, button: self.vscoLinkButton)

The error I am getting:

2017-01-13 21:22:58.675995 StudyHub[3328:27695] [error] error:  Failed to load model named DELETE
CoreData: error:  Failed to load model named DELETE
2017-01-13 21:22:58.699 StudyHub[3328:27695] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'An NSManagedObject of class 'UserDetails' must have a valid NSEntityDescription.'
*** First throw call stack:
(
0   CoreFoundation                      0x0000000114fa2d4b __exceptionPreprocess + 171
1   libobjc.A.dylib                     0x0000000114a0b21e objc_exception_throw + 48
2   CoreData                            0x000000010ffe0fb0 -[NSManagedObject initWithEntity:insertIntoManagedObjectContext:] + 528
3   StudyHub                            0x000000010edee13c _TFC8StudyHub11UserDetailscfT6entityCSo19NSEntityDescription10insertIntoGSqCSo22NSManagedObjectContext__S0_ + 76
4   StudyHub                            0x000000010edee212 _TToFC8StudyHub11UserDetailscfT6entityCSo19NSEntityDescription10insertIntoGSqCSo22NSManagedObjectContext__S0_ + 66
5   CoreData                            0x0000000110082d79 -[NSManagedObject initWithContext:] + 793
6   StudyHub                            0x000000010ed05dd4 _TTOFCSo15NSManagedObjectcfT7contextCSo22NSManagedObjectContext_S_ + 36
7   StudyHub                            0x000000010ed0211c _TFCSo15NSManagedObjectCfT7contextCSo22NSManagedObjectContext_S_ + 76
8   StudyHub                            0x000000010ed009e5 _TFFC8StudyHub11AppDelegate11applicationFTCSo13UIApplication29didFinishLaunchingWithOptionsGSqGVs10DictionaryVSC29UIApplicationLaunchOptionsKeyP____SbL_15saveUserDetailsFT4dataGS2_SSSS__T_ + 421
9   StudyHub                            0x000000010ed02837 _TFFC8StudyHub11AppDelegate11applicationFTCSo13UIApplication29didFinishLaunchingWithOptionsGSqGVs10DictionaryVSC29UIApplicationLaunchOptionsKeyP____SbU1_FCSo15FIRDataSnapshotT_ + 1607
10  StudyHub                            0x000000010ed0290c _TTRXFo_oCSo15FIRDataSnapshot__XFdCb_dS___ + 60
11  StudyHub                            0x000000010eedb4af __43-[FValueEventRegistration fireEvent:queue:]_block_invoke.57 + 78
12  libdispatch.dylib                   0x0000000115df3978 _dispatch_call_block_and_release + 12
13  libdispatch.dylib                   0x0000000115e1d0cd _dispatch_client_callout + 8
14  libdispatch.dylib                   0x0000000115dfd8a4 _dispatch_main_queue_callback_4CF + 406
15  CoreFoundation                      0x0000000114f66e49 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 9
16  CoreFoundation                      0x0000000114f2c37d __CFRunLoopRun + 2205
17  CoreFoundation                      0x0000000114f2b884 CFRunLoopRunSpecific + 420
18  GraphicsServices                    0x0000000117ba4a6f GSEventRunModal + 161
19  UIKit                               0x00000001131bfc68 UIApplicationMain + 159
20  StudyHub                            0x000000010ed04d4f main + 111
21  libdyld.dylib                       0x0000000115e6968d start + 1
22  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

回答1:

Try changing:

let container = NSPersistentContainer(name: "DELETE")

to this:

let container = NSPersistentContainer(name: "StudyHub")

According to documentation:

By default, the provided name value is used to name the persistent store and is used to look up the name of the NSManagedObjectModel object to be used with the NSPersistentContainer object.



回答2:

I had a similar problem. I went into App Delegate and found that let container = NSPersistentContainer(name: "Your App Name") didn't match the name of my data model.

I changed it to the name of my data model and it now works.