1

这是我的模型:

class Channel: Identifiable, Decodable, ObservableObject {
    
    var id = UUID()
    var channelId = ""
    var title = ""
    var thumbnail = ""
    @Published var thumbnailImage : UIImage?
    
    enum CodingKeys: String, CodingKey {
        
        //Keys not in the model
        case snippet
        case thumbnails
        case high
         
        //Keys in the model
        case channelId
        case title
        case thumbnail = "url"
    }
    
    required init (from decoder: Decoder) throws {
        
        let container =  try decoder.container(keyedBy: CodingKeys.self)
        let snippetContainer = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .snippet)
        let thumbnailsContainer = try snippetContainer.nestedContainer(keyedBy: CodingKeys.self, forKey: .thumbnails)
        let highContainer = try thumbnailsContainer.nestedContainer(keyedBy: CodingKeys.self, forKey: .high)
        
        self.title = try snippetContainer.decode(String.self, forKey: .title)
        self.thumbnail = try highContainer.decode(String.self, forKey: .thumbnail)
        self.channelId = try snippetContainer.decode(String.self, forKey: .channelId)
    }
}
class ChannelStore: ObservableObject {    
    @Published var allChannels = [Channel]()
}

我有一个链接到 ChannelStore 的 EnvironmentObject ,它都按预期工作。

问题是当属性 thumbnailImage 更改时我的视图需要更新。(由于它来自网络调用,因此视图在调用返回之前生成,同时使用库存图像)。我尝试将 Published 属性包装器添加到该属性,但它没有做任何事情。

在我看来,我有:@EnvironmentObject var channelStore: ChannelStore

如何订阅由 EnvironmentObject 管理的属性更改?

编辑

建议将 Channel 类更改为结构。我上课的唯一原因是避免“不能分配给属性:'channel'是'let'常量:

for channel in channelStore.allChannels {
    networking.setThumbnail(channel: channel) { image in
        channel.thumbnailImage = image
    }
}

最后的评论

通过使用下面提供的答案并将我的 for 循环更改为以下内容,我能够解决整个问题:

for (index, var channel) in channelStore.allChannels.enumerated() {
    networking.setThumbnail(channel: channel) { image in
        channel.thumbnailImage = image
        channelStore.allChannels[index] = channel
        print("Images LOADED")
    }
}
4

1 回答 1

1

如果你可以让你Channel的 a struct

struct Channel: Identifiable, Decodable { // <- replace `class` with `struct`
    ...
    var thumbnailImage : UIImage? // <- remove `@Published`
}

然后对 的每次修改thumbnailImage都会创建对象的新副本Channel并触发 中的@Published属性ChannelStore

class ChannelStore: ObservableObject {
    @Published var allChannels = [Channel]()
}
于 2020-07-22T21:13:17.187 回答