我有一个类(WatchlistClass),它符合“ObservableObject”协议(protocol)并保存@Published var(监视列表)。反过来,var 包含一整套股票和一些信息([StockInformation]),它应该用当前股票价格和其他内容更新我的 View (WatchlistView)。该部分工作得很好,但该类应该访问 View 中的 @StateObject 来更改数据。直接在类中访问它是行不通的,因为它不会从 @StateObject 读取数据。我尝试直接访问 View 中的 @StateObject,但这也创建了一个具有空数组的类的新实例。在 @Published var 上使用“static”会引发错误。我一生都无法弄清楚如何直接在 View 内访问 @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()
...
}
最佳答案
您的timer
是一个实例变量,但它的闭包不是该类的实例,并且没有self
。
您必须做一些事情才能将“self”放入计时器 block 的范围内。一种方法是在实例的成员函数中创建计时器:
private func makeTimer() -> Timer {
return Timer.scheduledTimer(withTimeInterval: 4.0, repeats: true) { [weak self] _ in
if let empty = self?.watchlist.isEmpty,
empty == false {
}
}
}
当您调用 makeTimer() 时,您的代码将在实例的上下文中执行。它将有权访问self
。
请注意,我已经更改了您的 block ,以便它“弱”捕获self
,因为计时器可能存在于对象的生命周期之外,因此您必须积极主动地应对这种可能性。
您可以从初始化程序中调用 makeTimer。
关于swift - 从 View 之外的函数访问@StateObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69861297/