You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI中@ObservedObject在willSet发送通知时的UI刷新时机疑问

Understanding willSet and objectWillChange in SwiftUI

Great question—this is such a common point of confusion when first learning how ObservableObject works with SwiftUI, so let’s break it down step by step.

First, let’s clarify the exact order of operations when you run self.value += 1:

  1. Swift calculates the new value (current value + 1) first.
  2. The willSet block runs before the new value is assigned to value—this is where you’re sending objectWillChange.send().
  3. The new value is actually stored in value.
  4. If there was a didSet block, it would run next (you don’t have one here).

Now, the key detail you’re missing: SwiftUI doesn’t refresh the UI immediately when it receives objectWillChange. Instead, that notification acts as a heads-up: “Something in this ObservableObject is about to change—plan to update the UI soon.”

SwiftUI batches these update requests and waits until the current chunk of code finishes executing before reloading the view. In your example, that means after the entire self.value += 1 operation is done (including assigning the new value to value), SwiftUI will re-run the body of ContentView and read the updated updater.value to display in the Text view.

To put it simply:

  • The notification goes out before the value changes, but
  • SwiftUI waits until the value has actually changed before it refreshes the UI to show the new number.

That’s why your app shows the updated value even though you’re sending the notification in willSet—the timing works out because SwiftUI delays the UI update just long enough for the value to finish updating.


内容的提问来源于stack exchange,提问作者Super Noob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 21:58:14