我有一个应用程序,该应用程序每天进行一次API调用以检索新数据。
应用启动后,它将检查是否有新数据可用,将新数据保存到核心数据中,调用核心数据以在视图中显示数据。
问题
将新数据保存到核心数据后,我的视图将不会显示新保存的数据,而是显示模型中的默认虚拟数据。重新启动应用程序后,将显示新数据。
问题
如何在视图中显示新保存的数据而无需重新启动应用程序?我正在使用MVVM模式。以下是我的代码以及指向我的代码的链接。
class UVIndexNowModel: ObservableObject
{
@Published var uvIndex: Int
@Published var dateTime: Date
init(uvIndex: Int = 0, dateTime: Date = Date())
{
self.uvIndex = uvIndex
self.dateTime = dateTime
}
}
class UVIndexNowViewModel: NSObject, ObservableObject
{
private var isFirstAppearance = true
private let moc = PersistentStore.shared.context
private let nowController: NSFetchedResultsController<UVHour>
@Published var data: UVIndexNowModel = UVIndexNowModel()
@Published var coreDateError: Bool = false
override init()
{
nowController = NSFetchedResultsController(fetchRequest: UVHour.uvIndexNowRequest,
managedObjectContext: moc,
sectionNameKeyPath: nil, cacheName: nil)
super.init()
nowController.delegate = self
do {
try nowController.performFetch()
let results = nowController.fetchedObjects ?? []
setUVIndex(from: results)
} catch {
print("failed to fetch items!")
}
}
func setUVIndex(from hours: [UVHour])
{
let date = Date()
let formatter = DateFormatter()
formatter.timeZone = .current
formatter.dateFormat = "MMM/d/yyyy hh a"
let todaystr = formatter.string(from: date)
print("UVIndexNowVM.setUVIndex() size of UVHour array: \(hours.count)")
for i in hours
{
let tempDateStr = formatter.string(from: i.wrappedDateTime)
if todaystr == tempDateStr
{
print("UV Now VM Date matches! \(tempDateStr)")
self.data.uvIndex = i.wrappedUVIndex
self.data.dateTime = i.wrappedDateTime
break
}
}
}
}
extension UVIndexNowViewModel: NSFetchedResultsControllerDelegate
{
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>)
{
print("UVIndexNowViewModel controllerDidChangeContent was called. New Stuff in DB")
guard let results = controller.fetchedObjects as? [UVHour] else { return }
setUVIndex(from: results)
}
}
struct UVIndexNowView: View {
@ObservedObject var vm = UVIndexNowViewModel()
var body: some View {
VStack {
Text("\(vm.data.dateTime)")
Text("UV Index: \(vm.data.uvIndex)")
}
}
}
答案 0 :(得分:1)
由于您的UVIndexNowModel
是ObservableObject
,因此您需要在单独的视图中进行观察,例如
struct UVIndexNowView: View {
@ObservedObject var vm = UVIndexNowViewModel()
var body: some View {
UVIndexNowDataView(data: vm.data) // << here !!
}
}
和
struct UVIndexNowDataView: View {
@ObservedObject var data: UVIndexNowModel
var body: some View {
VStack {
Text("\(data.dateTime)")
Text("UV Index: \(data.uvIndex)")
}
}
}