如何在小部件中获取核心数据

how to fetch coredata in widget

我正在尝试获取小部件中的核心数据。

在viewcontroller中,我成功获取了核心数据,但在widget.swift中,我无法获取我的核心数据。

这是我的代码

widget.swift

func getTimeline(for configuration: ConfigurationIntent, in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
        let containerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: <My GroupId>)!
        let storeURL = containerURL.appendingPathComponent("DataModel.sqlite")
        let description = NSPersistentStoreDescription(url: storeURL)

        let container = NSPersistentContainer(name: "Entity")
        container.persistentStoreDescriptions = [description]
        container.loadPersistentStores { description, error in
            if let error = error {
                fatalError("Unable to load persistent stores: \(error)")
            } }
        
        var yourResult : [Entity]?

        let moc = CoreDataStack.shared.managedObjectContext
        let predicate = NSPredicate(format: "name == %@", "test")
        let request = NSFetchRequest<Entity>(entityName: "Entity")
        let result = try? moc.fetch(request)

        request.predicate = NSPredicate(format: "attribute1 == %@", "test")
                do {
                    yourResult = try context.fetch(request) as? [Entity]
                    completion(yourResult)
                } catch let error as NSError{
                    print(error.localizedDescription)
                }
        
        var entries: [SimpleEntry] = []

        // Generate a timeline consisting of five entries an hour apart, starting from the current date.
        let currentDate = Date()
        for hourOffset in 0 ..< 5 {
            let entryDate = Calendar.current.date(byAdding: .hour, value: hourOffset, to: currentDate)!
            let entry = SimpleEntry(date: entryDate, configuration: configuration)
            entries.append(entry)
        }

        let timeline = Timeline(entries: entries, policy: .atEnd)
        completion(timeline)
    }

这条线 yourResult = 尝试 context.fetch(请求) 作为? [实体]

发生错误。

错误是 'Provider.Context' 类型的值(又名 'TimelineProviderContext')没有成员 'fetch'*

请帮帮我!!

您的 context 是在函数参数中定义的,因此它不是 CoreData 上下文,而是时间轴的 TimelineProviderContext

尝试使用以下代码获取数据,就像在添加谓词之前所做的那样:

yourResult = try moc.fetch(request) as? [Entity]