Реализация базовых данных в независимом приложении watchOS - PullRequest
1 голос
/ 07 октября 2019

Как я знаю, мы можем использовать Core Data в приложениях Apple Watch. Таким образом, независимое приложение watchOS может иметь собственный постоянный магазин. Но когда мы создаем проект для приложения watchOS, нет возможности использовать базовые данные (как, например, при создании проекта для приложения iOS)

Итак, как реализовать Core Data в независимом приложении watchOS?

Я скопировал этот код из приложения iOS (которое использует Core Data) и вставил его в ExtensionDelegate моего независимого приложения SwiftUI watchOS

 // 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: "CoreDataToDo")
        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)")
            }
        }
    }

Итак, что мне делать дальше?
или я уже делаю это неправильно?

Пожалуйста, помогите мне. Я так старался найти, как это сделать. Но я не могу найти хороших решений, потому что раньше не было независимых приложений для watchOS, поэтому большинство разработчиков не создавали отдельные постоянные магазины для приложений watchOS.
Так что, пожалуйста, помогите мне.
Спасибо.

1 Ответ

1 голос
/ 07 октября 2019

Вам также нужно убедиться, что у вас есть файл xcdatamodeld, тогда вам должно быть хорошо. См. Мой ответ на этот вопрос о том, как передать контекст управляемого объекта на View s и как правильно настроить подкласс WKHostingController.

...