接受的答案可能无法套上所有用例。
在我的情况下,我希望
Actor-isolated property 'num' can not be referenced from the main actor
保留一个ObservableObject
,但可以从Swiftui视图中访问其属性之一。所以我只添加
actor
@MainActor
您需要在视图模型上使用
actor Model: ObservableObject {
@MainActor @Published var num: Int = 0
func updateNumber(_ newNum: Int) {
Task { @MainActor in
self.num = newNum
}
}
// all other properties and functions will remain isolated to the actor
}
(命名
MainActor
),这表明其中所有派遣都在主线程上(当然,假设您将使用新的Swift并发系统为其)。所以看起来像
Model