【发布时间】:2021-11-06 03:45:28
【问题描述】:
我有一个符合“ObservableObject”协议的类(WatchlistClass),它拥有一个@Published var(监视列表)。反过来,var 包含一系列股票和一些信息([StockInformation]),它应该用当前的股票价格和东西更新我的视图(WatchlistView)。该部分工作得很好,但是该类应该访问视图中的@StateObject 以更改数据。直接在类中访问它是行不通的,因为它不会从@StateObject 读取数据。我尝试直接访问视图中的@StateObject,但这也创建了一个具有空数组的类的新实例。在 @Published var 上使用“静态”会引发错误。在我的一生中,我无法弄清楚如何直接在视图内访问 @StateObject 以读取和修改它所拥有的数据。任何帮助将不胜感激。
class WatchlistClass: ObservableObject {
static let shared = WatchlistClass()
@Published var watchlist: [StockInformation] = []
struct StockInformation: Identifiable {
...
}
func WatchlistTasksGetFundamentalsDelegate(string: String) {
...
DispatchQueue.main.async {
self.watchlist.append(stockInformation) // This works and updates the view as expected
}
...
}
private let timer = Timer.scheduledTimer(withTimeInterval: 4.0, repeats: true) { _ in
if self.watchlist.isEmpty == false { // This does not work
...
}
}
struct WatchlistView: View {
@StateObject var watchlistClass = WatchlistClass()
...
}
【问题讨论】:
-
这些答案是否回答了您的问题或对您有帮助?
-
很抱歉这么晚才回答,过去几天我没有 XCode 来尝试答案。
标签: swift swiftui property-wrapper