SwiftUI中@ObservedObject在willSet发送通知时的UI刷新时机疑问
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:
- Swift calculates the new value (current
value+ 1) first. - The
willSetblock runs before the new value is assigned tovalue—this is where you’re sendingobjectWillChange.send(). - The new value is actually stored in
value. - If there was a
didSetblock, 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

