核心数据 NSManagedObject 没有有效的 NSEntityDescription

问题描述 投票:0回答:3

我正在尝试使用 Xcode 项目设置核心数据,但遇到了一个我似乎无法摆脱的错误。我在

UserDetails
内部有一个名为
StudyHub.xcdatamodeld
的实体。我在 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
ios swift xcode core-data appdelegate
3个回答
5
投票

尝试改变:

let container = NSPersistentContainer(name: "DELETE")

对此:

let container = NSPersistentContainer(name: "StudyHub")

根据文档

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


4
投票

我也有类似的问题。我进入 App Delegate 并发现

let container = NSPersistentContainer(name: "Your App Name")
与我的数据模型的名称不匹配。

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


0
投票

如果您使用静态库中的 CoreData,请确保您的

module
名称和
codegen
,尝试这会起作用。

© www.soinside.com 2019 - 2024. All rights reserved.