SwiftUI 中有没有一种方法可以将数据从 属性 传输和处理到 class?

Is there a way in SwiftUI to transport and handle data from an property to the class?

我这里有两个类。 Music用于存储音乐url和加载元数据,MusicManager用于存储音乐列表并在所有音乐的元数据加载完成后对它们进行排序。

由于每个音乐 let metadata = try? await asset.load(.commonMetadata) 的元数据加载是异步的,我无法直接调用 init() 中的排序函数。

我试图在 Combine 框架中使用 Publisher 找到一些解决方案,当加载元数据时,发布者将发出一个完成,如果 MusicManager 收到足够的完成(与音乐列表的计数相同),它将执行排序。

class Music: ObservableObject, Identifiable {
    static let publisher = PassthroughSubject<Void,Error>
......
}

class MusicManager: ObservableObject {
......
    static var count = 0
    let subscriber = Music.pub.sink { completion in
        switch completion {
        case .finished:
            count += 1
            if musicList.count == count {
                ......
            }
        case .failure(_):
        }
    } receiveValue: { _ in }
......
}

但是它说Instance member 'library' cannot be used on type 'MusicListManager'; did you mean to use a value of this type instead?

当所有音乐的元数据都已加载时,如何通知我。如果您能给我一些建议,我将不胜感激。

我们通常不会将 sinkObservableObject 一起使用,而是 assign Combine 管道的末端到 @Published 这也使管道与对象相同,因此无需存储可取消项。

但是,您提到您正在使用 async/await。如果使用它,您不再需要 ObservableObject。只需将资产作为 let 参数传递到您的 View 中,然后使用 task 修饰符调用您的 async/await 代码并设置一个 @State 结果将导致 body被调用。 SwiftUI 将计算 View 层次结构差异并使用更改更新屏幕上的 UIKit/AppKit 视图。