gpt4 book ai didi

swift - entityForName : nil is not a legal NSPersistentStoreCoordinator for searching for entity name

转载 作者:行者123 更新时间:2023-12-04 13:57:09 24 4
gpt4 key购买 nike

我设置了一个 DatabaseApplicationService

  • 获取以编程方式定义的 NSManagedObjectModel
  • 基于这个模型创建一个NSPersistentCloudKitContainer,有“Local”和“Cloud”两种配置。

  • 看起来这一切都很好。
        lazy var persistentContainer: NSPersistentCloudKitContainer = {

    // Ensure that we have the required path.
    pathHandler.ensurePersistentStorePath()

    #if DEBUG
    // get the store description
    guard let description = container.persistentStoreDescriptions.first
    else {
    fatalError("Could not retrieve a persistent store description.")
    }

    // initialize the CloudKit schema
    try? container.initializeCloudKitSchema(options: NSPersistentCloudKitContainerSchemaInitializationOptions.dryRun)

    #endif

    let local = NSPersistentStoreDescription(url: pathHandler.persistentLocalStoreURL)
    local.configuration = "Local"

    let cloud = NSPersistentStoreDescription(url: pathHandler.persistentCloudStoreURL)
    cloud.configuration = "Cloud"

    cloud.cloudKitContainerOptions = NSPersistentCloudKitContainerOptions(containerIdentifier: "iCloud.com.innoreq.HappyFreelancer")
    container.persistentStoreDescriptions = [ local, cloud ]

    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
    }()


    SceneDelegate ,环境获取注入(inject)的 NSManagedObjectContext:
            let contentView = ContentView().environment(\.managedObjectContext, databaseService.context)

    在 View 的模型中,环境被要求提供上下文:
        @Environment(\.managedObjectContext) var managedObjectContext: NSManagedObjectContext

    现在,从上下文中获取数据时:
    let fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "EWork")

    do {

    return try managedObjectContext.execute(fetchRequest) as! [IsTimedAndTagged]
    } catch {

    fatalError("Failed to fetch EWork")
    }

    在运行时抛出此错误:
    2020-01-23 16:34:05.981483+0100 XY[14121:20859222] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+entityForName: nil is not a legal NSPersistentStoreCoordinator for searching for entity name 'EWork''

    检查服务的协调器时,它不为零。对这种奇怪的效果有什么解释吗?

    最佳答案

    对于那些使用 Swift5 并且没有 Appdelegate 并尝试创建 NFSRequest 查询的人。
    您可能缺少持久存储,因此创建您自己的自定义存储可能会起作用。因为那是我的问题。
    创建您自己的 PersistentContainer 类:

    import SwiftUI
    import CoreData
    @main
    struct TestApp: App {
    let context = PersistentCloudKitContainer.persistentContainer.viewContext
    var body: some Scene {
    WindowGroup {
    ContentView().environment(\.managedObjectContext, context)
    }
    }
    }
    然后你的自定义类是这样的:
    import CoreData
    public class PersistentCloudKitContainer {
    // MARK: - Define Constants / Variables
    public static var context: NSManagedObjectContext {
    return persistentContainer.viewContext
    }
    // MARK: - Initializer
    private init() {}
    // MARK: - Core Data stack
    public static var persistentContainer: NSPersistentContainer = {
    let container = NSPersistentContainer(name: "Model")
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
    if let error = error as NSError? {
    fatalError("Unresolved error \(error), \(error.userInfo)")
    }
    })
    container.viewContext.automaticallyMergesChangesFromParent = true
    container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
    return container
    }()
    // MARK: - Core Data Saving support
    public 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)")
    }
    }
    }
    }
    希望它可以帮助像我这样的人,他们最终可能会在这里寻找答案!

    关于swift - entityForName : nil is not a legal NSPersistentStoreCoordinator for searching for entity name,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59882156/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com