我正在学习 SwiftUI。我遇到了一个问题。我试图更新数组的值,但它没有更新。还请指导我如何创建对象数组并更新用户界面。还更新 ui 并且数组中的任何对象都得到更新。
我正在使用的当前代码如下:
@State var unsafeInboxList: [Inbox] = []
private func observeNewChatMessage(userId: String){
let inboxRef = databaseReference.child(DatabaseNode.Root.inbox.rawValue)
.child(userId)
inboxRef.observe(.childAdded, with: { (snapshot) in
guard let value = snapshot.value else { return }
var inbox = Inbox(with: JSON(value))
self.addNew(inboxItem: inbox)
inbox.roomType = .single
self.observeRoomDetails(inbox: inbox)
self.getBlockLeaveLastMessage(roomId: inbox.roomId, completion: { (lastMessage) in
if let lastMessage = lastMessage{
self.update(lastMessage: lastMessage, inbox: inbox)
}else{
self.setLastMessageObserver(inbox: inbox)
}
})
})
}
private let inboxQueue = DispatchQueue(label: "InboxQueue", attributes: .concurrent)
private func addNew(inboxItem inbox: Inbox){
inboxQueue.async(flags: .barrier) {
if let index = self.unsafeInboxList.firstIndex(of: inbox){
_ = self.unsafeInboxList[index]
var nInbox = inbox
nInbox.chatMember = self.unsafeInboxList[index].chatMember
nInbox.chatRoom = self.unsafeInboxList[index].chatRoom
//nInbox.unreadCount = self.unsafeInboxList[index].unreadCount
self.unsafeInboxList[index] = nInbox
}else{
self.unsafeInboxList.append(inbox)
}
self.sortListing()
}
}
private func observeRoomDetails(inbox: Inbox){
let roomRef = databaseReference.child(DatabaseNode.Root.roomInfo.rawValue).child(inbox.roomId)
roomRef.observe(.value, with: { (snapshot) in
if let value = snapshot.value{
let chatRoom = ChatRoom(with: JSON(value))
self.update(inboxItem: inbox, chatRoom: chatRoom)
}
})
}
在这里,当我尝试使用新聊天室更新对象时,值没有更新,并且我正在获取以前的收件箱对象。
private func update(inboxItem inbox: Inbox, chatRoom: ChatRoom){
inboxQueue.async(flags: .barrier) {
if let index = self.unsafeInboxList.firstIndex(of: inbox){
self.unsafeInboxList[index].chatRoom = chatRoom
// chatroom updated
}
self.sortListing()
}
}