核心数据 NSManagedObject 没有有效的 NSEntityDescription

Posted

技术标签:

【中文标题】核心数据 NSManagedObject 没有有效的 NSEntityDescription【英文标题】:Core Data NSManagedObject doesn't have a valid NSEntityDescription 【发布时间】:2017-01-14 02:37:46 【问题描述】:

我正在尝试使用我的 Xcode 项目设置核心数据,但遇到了一个我似乎无法摆脱的错误。我在StudyHub.xcdatamodeld 中有一个名为UserDetails 的实体。我在 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()

我用于检索存储在 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)

我得到的错误:

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

【问题讨论】:

模特的名字不应该是StudyHub而不是DELETE吗? 【参考方案1】:

尝试改变:

let container = NSPersistentContainer(name: "DELETE")

到这里:

let container = NSPersistentContainer(name: "StudyHub")

根据documentation:

默认情况下,提供的名称值用于命名持久存储,并用于查找要与 NSPersistentContainer 对象一起使用的 NSManagedObjectModel 对象的名称。

【讨论】:

【参考方案2】:

我遇到了类似的问题。我进入 App Delegate 发现 let container = NSPersistentContainer(name: "Your App Name") 与我的数据模型的名称不匹配。

我将其更改为我的数据模型的名称,现在它可以工作了。

【讨论】:

以上是关于核心数据 NSManagedObject 没有有效的 NSEntityDescription的主要内容,如果未能解决你的问题,请参考以下文章

如何有效地从 NSManagedObject 中获取属性的所有有效值?

核心数据 NSManagedObject:最大属性数?

核心数据 - 遍历 NSManagedObject 的属性

iOS 14 Beta - Swift UI 中的核心数据错误:任何模型中都没有 NSEntityDescriptions 声明 NSManagedObject 子类

在 Xcode 6 中从核心数据数据模型创建 NSManagedObject 子类

NSManagedObject 的设置属性阻止了核心数据中的 iPad UI'