![](/img/trans.png)
[英]How can I store multiple instances of different data with the same keyword in Firebase using Swift?
[英]How do I deal with multiple widget instances accessing the same CoreData store?
背景資料
我有一個主應用程序,它將單個條目寫入應用程序組中包含的數據庫(我們分別稱它們為“DB1”和“Group1”)。 在同一個項目中,我添加了一個 iOS 14 主屏幕小部件擴展。 然后將此擴展添加到 Group1。
所有三種尺寸(小、中、大)都顯示來自 DB1 條目的相同信息,只是重新排列,對於較小的小部件,省略了一些部分。
問題
問題是,如果我有多個小部件實例(比如小型和中型),那么當我重建目標並加載/運行時,我會收到 CoreData 錯誤,如下所示:
<NSPersistentStoreCoordinator: 0x---MEM--->: Attempting recovery from error encountered during addPersistentStore: Error Domain=NSCocoaErrorDomain Code=134081 "(null)" UserInfo={NSUnderlyingException=Can't add the same store twice}
相關代碼
這是時間線 function 的代碼
public func timeline(with context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
//Set up widget to refresh every minute
let currentDate = Date()
let refreshDate = Calendar.current.date(byAdding: .minute, value: 1, to: currentDate)!
WidgetDataSource.shared.loadTimelineEntry { entry in
guard let e = entry else { return }
let entries: [TimelineEntry] = [e]
let timeline = Timeline(entries: entries, policy: .after(refreshDate))
completion(timeline)
}
}
這是 loadTimelineEntry function
(persistentContainer 在 WidgetDataSource 的 init() 中初始化,class 包含 loadTimelineEntry 函數)
func loadTimelineEntry(callback: @escaping (TimelineEntry?) -> Void) {
persistentContainer.loadPersistentStores(completionHandler: { (storeDescription, error) in
print("Loading persistent stores")
var widgetData: [WidgetData]
if let error = error {
print("Unresolved error \(error)")
callback(nil)
} else {
let request = WidgetData.createFetchRequest()
do {
widgetData = try self.persistentContainer.viewContext.fetch(request)
guard let data = widgetData.first else { callback(nil); return }
print("Got \(widgetData.count) WidgetData records")
let entry = TimelineEntry(date: Date())
callback(entry)
} catch {
print("Fetch failed")
callback(nil)
}
}
})
}
老實說,我嘗試過的東西不多。 在將小部件放入 Group1 之前,我遇到了同樣的錯誤。 那是因為主應用程序在第一次運行時已經創建了 DB1,然后在隨后的小部件運行中,它查看了它自己的容器,沒有找到它,並試圖創建它自己的 DB1,而操作系統沒有不要因為他們有相同的名字而讓它。
小部件是一個相當新的功能,關於這個特定用例的問題並不多,但我敢肯定有人有類似的設置。 任何幫助或提示將不勝感激!
感謝 Tom Harrington 的評論,我能夠通過在我的 loadTimelineEntry function 頂部添加一個檢查來解決警告,如下所示:
if !persistentContainer.persistentStoreCoordinator.persistentStores.isEmpty {
//Proceed with fetch requests, etc. w/o loading stores
} else {
//Original logic to load store, and fetch data
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.