0

我正在开发一个同时使用 iCloud Documents 和新 CloudKit 的应用程序。这两项服务在“签名和功能”下的 iCloud 部分都处于活动状态。

XCode 中的 iCloud 服务和容器

因为整个app都用到了CloudKit,所以我会在appDelegate中像这样实例化

 lazy var persistentContainer: NSPersistentCloudKitContainer = {
        let container = NSPersistentCloudKitContainer(name: "MyTestApp")

        container.loadPersistentStores(completionHandler: { _, error in
            if let error = error as NSError? {
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })

        container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
        container.viewContext.automaticallyMergesChangesFromParent = true

        return container
    }()

并通过提供

struct MyTestApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

    var body: some Scene {
        WindowGroup {
            ContentView()
                .environment(\.managedObjectContext, appDelegate.persistentContainer.viewContext)
        }
    }
}

在应用程序的视图中,我试图从 iCloud Documents 访问数据,所以我正在做的是:

struct TestReadICDView: View {
    private let iCloudDocumentsURL = FileManager.default.url(forUbiquityContainerIdentifier: "iCloud.it.mytestapp.oldcontainer")?.appendingPathComponent("MyTestApp.sqlite")

    init() {
        guard let modelURL = Bundle.main.url(forResource: "MyTestApp", withExtension: "momd") else {
            fatalError("Error loading model from bundle")
        }

        guard let mom = NSManagedObjectModel(contentsOf: modelURL) else {
            fatalError("Error initializing mom from: \(modelURL)")
        }

        let psc = NSPersistentStoreCoordinator(managedObjectModel: mom)

        let context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)

        context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy

        context.persistentStoreCoordinator = psc

        do {
            try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: iCloudDocumentsURL, options: nil)
            let fetchRequest: NSFetchRequest<Nota> = Nota.fetchRequest()
            let data = try context.fetch(fetchRequest)
            print("count: \(data.count)")
        } catch {
            fatalError("Error adding store: \(error)")
        }
    }

    var body: some View {
        Text("Hello World!")
    }
}

但是每次我进入视图时,我都会得到:

Thread 1: "executeFetchRequest:error: A fetch request must have an entity."

但是实体是在 NSFetchRequest 中指定的。

我不明白为什么

4

0 回答 0