在另一个视图中更新核心数据实体后,SwiftUI 列表视图未更新

Zen*_*n C 4 core-data swift swiftui

我有一个存储在核心数据中的课程实体,其变量之一是存储课程是否完成。

这些课程列在 SwiftUI 列表中,选择后会转到游戏所在的视图。游戏完成后,complete 变量将更新为 true。应该发生的情况是列表视图显示列出的游戏,并在游戏旁边显示一个复选标记。

然而,发生的情况是,当我在游戏中保存课程的“已完成”状态时(在 tapRight 方法中 - 见下文),我收到警告:

[TableView] 仅警告一次:UITableView 被告知在不位于视图层次结构中的情况下布局其可见单元格和其他内容(表视图或其超级视图之一尚未添加到窗口中)。

然后,当我通过按游戏视图顶部的导航按钮返回列表视图时,我发现游戏已从列表中消失。

但是,当我关闭应用程序并重新打开它时,列表中包含游戏行和复选标记,因此我知道核心数据课程实例正在正确更新。下面的列表视图代码。

import SwiftUI
import CoreData
import UIKit

struct LessonList: View {

@Environment(\.managedObjectContext) var moc

@State private var refreshing = false
private var didSave =  NotificationCenter.default.publisher(for: .NSManagedObjectContextDidSave)

@FetchRequest(entity: Lesson.entity(), sortDescriptors: [], predicate: NSPredicate(format: "(type == %@) AND (stage == %@) AND ((complete == %@) OR (complete == %@))", "phonicIntro", "1", NSNumber(value: true), NSNumber(value: false) )) var phonicIntroLessons1: FetchedResults<Lesson>

var body: some View {

    NavigationView {      
        List {
            self.stage1Section
        }
        .navigationBarTitle("Lessons")
    }
}


private var phonicIntroLink : some View {
    ForEach(phonicIntroLessons1) { lesson in
        NavigationLink(destination: PhonicIntroGame(lesson: lesson)) {
            LessonRow(lesson: lesson)
        }
    }
}

private var stage1Section : some View {
    Section(header: Text("Stage 1")) {
        phonicIntroLink
    }.onReceive(self.didSave) { _ in
        self.refreshing.toggle()
    }
}
Run Code Online (Sandbox Code Playgroud)

游戏View中保存完成状态的相关代码:

import SwiftUI
import AVFoundation

struct PhonicIntroGame: View {

@Environment(\.managedObjectContext) var moc

var lesson: Lesson?

func tapRight() {
    if ((self.lesson?.phonicsArray.count ?? 1) - 1) > self.index {
        self.index = self.index + 1
        print("This is index \(self.index)")
        //On completion
        if (index + 1)  == (lesson!.phonicsArray.count) {
            self.lessonComplete()
        }
    } else {
        print(self.index)

func lessonComplete() {
    self.lesson?.setComplete(true)
    self.saveLesson()
}

func saveLesson() {
    do {
        try moc.save()
    } catch {
        print("Error saving context \(error)")
    }
}
Run Code Online (Sandbox Code Playgroud)

在 NSManagedObject 子类中:

extension Lesson {

func setComplete (_ state: Bool) {
    objectWillChange.send()
    self.complete = state
}
}
Run Code Online (Sandbox Code Playgroud)

LessonRow的代码如下:

import SwiftUI
import CoreData

struct LessonRow: View {

@Environment(\.managedObjectContext) var moc
@State var refreshing1 = false
var didSave =  NotificationCenter.default.publisher(for: .NSManagedObjectContextDidSave)
var lesson: Lesson

var body: some View {
        HStack {
            Image(lesson.wrappedLessonImage )
                .resizable()
                .frame(width: 80, height: 80)
                .cornerRadius(20)

            Text(lesson.wrappedTitle)
                .font(.system(size: 20))
                .fontWeight(.thin)
                .padding()

            if lesson.complete == true {
                Image(systemName: "checkmark.circle")
                    .resizable()
                    .frame(width: 30, height: 30)
                    .foregroundColor(.green)
            } else {
                Rectangle()
                    .frame(width: 30, height: 30)
                    .foregroundColor(.clear)
            }
        }.padding()
            .onReceive(self.didSave) { _ in
                self.refreshing1.toggle()
            }


   }
}
Run Code Online (Sandbox Code Playgroud)

我尝试过的事情:

  1. 强制列表重新加载通知和 .onReceive
  2. 使用 setComplete 函数设置 Lesson NSManagedObject 子类,该函数调用“objectWillChange”
  3. 通过包含完整变量的 true 和 false 使 @FetchRequest 更加详细

对于如何解决此问题的任何建议,我将不胜感激。我是 SwiftUI 的新手,所以提前感谢您的帮助。

Zen*_*n C 6

是的,我最终解决这个问题的方法是将 @ObservedObject 添加到 PhonicIntroGame : View 中的存储对象中。如下 -

@ObservedObject var lesson: Lesson
Run Code Online (Sandbox Code Playgroud)