2025-07-12 17:33:00

@MainActor 是干嘛用的?

@MainActor is a Swift attribute that ensures code runs on the main thread/main actor. It’s used to guarantee UI updates and other main-thread-only operations execute safely.

Key uses:

  • Classes/structs that update UI
  • Properties/methods that must run on main thread
  • Preventing data races in concurrent code
  • SwiftUI view models and UI-related code

Example:
@MainActor
class ViewModel: ObservableObject {
@Published var data: String = “”

  func updateUI() {
      // Always runs on main thread
      data = "Updated"
  }

}

本文链接:http://blog.go2live.cn/post/swift_main_actor.html

-- EOF --