我有一个ObservableObject
类和一个 SwiftUI 视图。当点击按钮时,我会在其中创建Task
并调用(异步函数)。populate
我以为这会populate
在后台线程上执行,但整个 UI 都冻结了。这是我的代码:
class ViewModel: ObservableObject {
@Published var items = [String]()
func populate() async {
var items = [String]()
for i in 0 ..< 4_000_000 { /// this usually takes a couple seconds
items.append("\(i)")
}
self.items = items
}
}
struct ContentView: View {
@StateObject var model = ViewModel()
@State var rotation = CGFloat(0)
var body: some View {
Button {
Task {
await model.populate()
}
} label: { …
Run Code Online (Sandbox Code Playgroud)