如何与小部件共享核心数据?

发布于 2025-02-01 15:00:37 字数 2556 浏览 5 评论 0原文

我想与小部件共享核心数据。我想我需要创建应用程序组(我知道如何做到这一点)。 但是,如何与小部件共享核心数据数据库?

如果我想在应用程序中使用核心数据,我总是只需创建一个新的Xcode项目并检查“使用核心数据”,然后获得此代码(Persistence.swift - 下面),它可以吸引我到数据库。

如何修改它,以便与小部件共享此核心数据数据库?

持久性

import CoreData

struct PersistenceController {
    static let shared = PersistenceController()

    static var preview: PersistenceController = {
        let result = PersistenceController(inMemory: true)
        let viewContext = result.container.viewContext
        for _ in 0..<10 {
            let newItem = Item(context: viewContext)
            newItem.timestamp = Date()
        }
        do {
            try viewContext.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)")
        }
        return result
    }()

    let container: NSPersistentContainer

    init(inMemory: Bool = false) {
        container = NSPersistentContainer(name: "MyAppName")
        if inMemory {
            container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
        }
        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)")
            }
        })
        container.viewContext.automaticallyMergesChangesFromParent = true
    }
}

I want to share Core Data with the Widget. I guess I'll need to create App Group (I know how to do this).
But how do I then share the Core Data database with the Widget?

If I wanna use Core Data in my app, I always just simply create a new Xcode project and check "Use Core Data", and I get this code (Persistence.swift - below), which hooks me up to a database.

How can I modify it, so that this Core Data database is shared with the Widget?

Persistence.swift

import CoreData

struct PersistenceController {
    static let shared = PersistenceController()

    static var preview: PersistenceController = {
        let result = PersistenceController(inMemory: true)
        let viewContext = result.container.viewContext
        for _ in 0..<10 {
            let newItem = Item(context: viewContext)
            newItem.timestamp = Date()
        }
        do {
            try viewContext.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)")
        }
        return result
    }()

    let container: NSPersistentContainer

    init(inMemory: Bool = false) {
        container = NSPersistentContainer(name: "MyAppName")
        if inMemory {
            container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
        }
        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)")
            }
        })
        container.viewContext.automaticallyMergesChangesFromParent = true
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

讽刺将军 2025-02-08 15:00:38

persistenceController类中,首先添加一个属性以获取应用程序组的URL

var containerURL: URL {
   return FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.myappname")!
}

,然后在持久容器的商店描述中设置URL

init(inMemory: Bool = false) {
    container = NSPersistentContainer(name: "MyAppName")
    if inMemory {
        container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
    } else {
        let storeURL = containerURL.appendingPathComponent("MyAppName.sqlite")
        container.persistentStoreDescriptions.first!.url = storeURL
    }
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in ...

,用您的实际数据替换字符串文字。

In the PersistenceController class first add a property to get the URL of the App Group

var containerURL: URL {
   return FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.myappname")!
}

then set the URL in the store descriptions of the persistent container

init(inMemory: Bool = false) {
    container = NSPersistentContainer(name: "MyAppName")
    if inMemory {
        container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
    } else {
        let storeURL = containerURL.appendingPathComponent("MyAppName.sqlite")
        container.persistentStoreDescriptions.first!.url = storeURL
    }
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in ...

Replace the string literals with your actual data.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文