我插入项目时,SwiftUI Core Data列表未排序,关闭并重新打开子视图

我试图为iOS创建一个SwiftUI应用 我有一个父亲视图,其中包含按上次活动日期排序的聊天室列表,当我打开子视图(聊天视图)并发送消息存储在核心数据中时,该视图关闭并再次打开,我尝试过视图中的FetchRequest

请注意,在下面的示例中,我删除了所有不必要的代码,仅在生成错误的TextField中显示了代码片段。 我的密码


struct ChatsView: View {
    @ObservedObject var chatsVM: ChatsVM = ChatsVM()

    var body: some View {
        GeometryReader { geometry in
            NavigationView {
                VStack {
                    List {

                                ForEach(self.search(self.chatsVM.rooms), id: \.self) { room in
                                    NavigationLink(destination: ChatView(room: room)){
                                        RoomItemView()
                                            .environmentObject(room)
                                            .listRowInsets(EdgeInsets())
                                    }
                                }

                    }
                }
                .navigationBarTitle(Text("Chats"))
            }
            .navigationViewStyle(StackNavigationViewStyle())
        }
    }

}

这是聊天视图


struct ChatView: View {
    @FetchRequest var messages: FetchedResults<MessageCD>

    init(room: RoomCD) {
        self.chatVM = ChatVM(room: room)
        // Do some kind of control flow for customizing the predicate here.
        self._messages = FetchRequest(
            entity: MessageCD.entity(),
            sortDescriptors: [NSSortDescriptor(key: "createdAt", ascending: false)],
            predicate: NSPredicate(format: "room == %@", room)
        )
    }

    var body: some View {
        GeometryReader { geometry in
            VStack {
                VStack(alignment: .center, spacing: 5) {
                    ZStack {
                        VStack(spacing: 0) {
                            if self.chatVM.isImageEditing {
                                VStack {
                                    PreviewToSendView(inputImage: self.$chatVM.imageSelected, isEditting: self.$chatVM.isImageEditing, url: self.$chatVM.urlFile)
                                }
                            } else{
                                Rectangle()
                                    .fill(Color.clear)
                                    .frame(height: 40)
                                self.messagesList

                                if self.chatVM.urlFile != nil {
                                    self.documentPreview
                                }
                            }
                            self.messageOptionsAndInput
                        }
                        VStack {
                            if !self.chatVM.isImageEditing {
                                self.countdown
                            }
                            Spacer()
                        }
                    }
                    .onReceive(
                        NotificationCenter.default.publisher(for: UIResponder.keyboardWillChangeFrameNotification)
                            .receive(on: RunLoop.main),
                        perform: self.updateKeyboardHeight
                    )
                    .onReceive(NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
                        print("Moving back to the foreground!")
                    }
                }

            }
                .navigationBarHidden(self.chatVM.isImageEditing)
                .navigationBarTitle("", displayMode: .inline)
                .navigationBarBackButtonHidden(true)
                .navigationBarItems(trailing:
                    HStack {
                        if self.chatVM.isImageEditing {
                            EmptyView()
                        } else {
                            self.titleBar
                            .frame(width: (geometry.size.width * 1) - 20)
                        }
                    }
                )
                .padding(.bottom, self.keyboardHeight)
                .transition(.slide)
                .animation(.easeIn(duration: self.keyboardAnimationDuration))
                .animation(.easeOut(duration: self.keyboardAnimationDuration))
                .edgesIgnoringSafeArea((self.keyboardHeight > 0) ? [.bottom] : [])
        }
    }

    func sendMessageText() {
        self.chatVM.sendMessage(text: self.typingMessage ?? "")
        self.typingMessage = nil
        self.chatVM.isImageEditing = false
        self.endEditing(true)
    }

    private var messagesList: some View {
        List {
                ForEach(messages, id: \.self) { message in
                    MessageView(currentMessage: message)
                        .transition(.fade)
                        .animation(.easeIn)
                        .scaleEffect(x: 1, y: -1, anchor: .center)
                        .listRowInsets(EdgeInsets())
                }

        }
            .listSeparatorStyleNone()
            .onAppear() {
                self.chatVM.seenMessages()
            }
            .scaleEffect(x: 1, y: -1, anchor: .center)
            .listRowInsets(EdgeInsets())
            .padding(5)
    }

}

和ObservableObject


class ChatVM: ObservableObject {
    private let managedObjectContext: NSManagedObjectContext
    private let sessionService = SessionService.shared
    private let socketIO = SocketIOManager.sharedInstance
    @Published var room: RoomCD

//    Image
    @Published var imageSelected: UIImage? = nil
    @Published var showImagePicker: Bool = false
    @Published var isImageEditing: Bool = false
//    Doc
    @Published var showDoc: Bool = false
    @Published var isLoading = false
    @Published var urlFile:URL? = nil

//    Camera
    @Published var showCameraPicker: Bool = false

//    IncidentView
    @Published var showIncidentView: Bool = false

//    Video
    @State var dataFile: Data? = nil

    init(room: RoomCD) {
        let context = AppDelegate.shared.persistentContainer.viewContext
        self.managedObjectContext = context
        self.room = room
    }

    func sendMessage(text: String) {
        let text = text.trimmingCharacters(in: .whitespacesAndNewlines)
        let message = self.handleSendMessage(text: text)

        self.sendToServer(text, message)

        self.imageSelected = nil
        self.dataFile = nil
        self.urlFile = nil
    }

    func handleSendMessage(text: String) -> MessageCD {
        let message = MessageCD(context: self.managedObjectContext)
        message.text = text
        message.isMyMessage = true
        message.id = UUID()
        message.status = 0
        message.createdAt = Date()
        message.room = room
        if let userS = self.sessionService.user,
            let userOwner = userS.getUserDB() {
            message.owner = userOwner
        }
        room.addToMessages(message)
        room.lastMessage = message
        room.lastActivity = Date()
        return message
    }

    func sendToServer(_ text: String, _ message: MessageCD) {
        var param = JsonDictionary()
        param["room"] = room.m_id ?? ""
        param["text"] = text
        DispatchQueue.global(qos: .background).async {

                APICaller.shared.callSendMessage(params: param) { (isSuccess, messageStr, json) in
                    print("json js", json)
                    DispatchQueue.global(qos: .background).async {
                        guard let newMessageJs = json["message"] as? JsonDictionary else {
                            return
                        }
                        self.managedObjectContext.perform {
                            message.initFrom(json: newMessageJs)
                            message.status = 2
                            self.managedObjectContext.saveIfNeeded()
                            self.socketIO.sendMessage(dataJs: json)
                        }
                    }
                }
    }
}