skip to content

A Swift NSObject subclass's property is observed with KVO, yet assignments made from Swift never notify; why does it need @objc dynamic?

level: seniorimportance: should knowfreq 45%

answer

  1. who calls the setter, and how
  2. entry point versus dispatch
  3. KVO intercepts through the runtime
  4. setValue(_:forKey:) behaves differently

basics

~20 s

KVO notifies by intercepting the setter through the Objective-C runtime. @objc only adds an Objective-C entry point; Swift callers still reach the setter through Swift's own dispatch and bypass the interception. dynamic forces every access through Objective-C messaging, so the observer fires.

solid answer

~40 s

Key-value observing works by replacing the observed object's setter at run time through the Objective-C runtime, then posting change notifications around the original. `@objc` gives the property an Objective-C entry point, so Objective-C code and `setValue(_:forKey:)` go through the intercepted setter, but Swift code assigning `job.bytesSent = 1024` still uses Swift's own dispatch and never reaches it. `dynamic` makes every access, from Swift too, an Objective-C message send that the compiler may not inline or devirtualize, so the replacement is honoured. The compiler warns when `observe(_:options:changeHandler:)` gets a key path to a property that is not `@objc dynamic`. In Swift 6.4, `dynamic` without `@objc` compiles but creates no Objective-C entry point, so it does not help KVO. The same applies to replacing a method's implementation through the Objective-C runtime.

code

swift · 20 lines
swift
import Foundation

final class UploadJob: NSObject {
  @objc dynamic var progress: Double = 0
  @objc var bytesSent: Int = 0          // @objc but not dynamic
}

let job = UploadJob()
var seen: [String] = []
let o1 = job.observe(\.progress, options: [.new]) { _, change in
  seen.append("progress \(change.newValue ?? -1)")
}
let o2 = job.observe(\.bytesSent, options: [.new]) { _, change in
  seen.append("bytesSent \(change.newValue ?? -1)")
}
job.progress = 0.5                      // notifies
job.bytesSent = 1024                    // silently missed
job.setValue(2048, forKey: "bytesSent") // notifies: goes through Objective-C
print(seen)
_ = (o1, o2)

go deeper

for a junior

Remember the rule of thumb: a Swift property observed with KVO is declared @objc dynamic, and the class inherits from NSObject.

for a middle

Explain the split: @objc creates an Objective-C entry point, dynamic routes every access through Objective-C messaging, and KVO needs both.

for a senior

Diagnose the half-working observer: Objective-C and setValue(_:forKey:) notify while Swift assignments do not, and the compiler's KVO warning already pointed at it.

for a principal

Limit @objc dynamic to properties that Objective-C observers really need during a migration, and move Swift-only observation off the Objective-C runtime.

## The symptom An Objective-C screen observes `uploadJob.bytesSent` with key-value observing (KVO), or Swift code calls `observe(\.bytesSent, options: [.new])` on an `NSObject` subclass. Changes made with `setValue(_:forKey:)`, or from Objective-C, notify. Changes assigned in Swift, `job.bytesSent = 1024`, do not. Nothing crashes; the observer is simply never called. The bug tends to appear during a migration, when code that used to set the property from Objective-C is rewritten in Swift and an Objective-C screen that observes it stops updating. ## How KVO notices a change KVO is a Foundation mechanism built on the Objective-C runtime. When the first observer is added, the runtime arranges for the object's setter to be replaced by one that announces the change before and after calling the original. Only a caller that reaches the setter **through Objective-C messaging** runs the replacement. The exact runtime technique belongs to the Objective-C material; for Swift the point is who goes through the runtime. ## What `@objc` and `dynamic` each add | Declaration | Objective-C entry point | Swift callers dispatch through | KVO from Swift assignment | |---|---|---|---| | `var bytesSent` | none | Swift dispatch | not reachable by KVO | | `@objc var bytesSent` | yes | Swift dispatch (direct or vtable) | **missed** | | `@objc dynamic var progress` | yes | Objective-C message send | **notifies** | | `dynamic var level` (no `@objc`) | none | Swift's own dynamic mechanism | not reachable by KVO | - **`@objc`** exposes the property to Objective-C: a selector, a thunk and metadata. Objective-C callers and Foundation's string-keyed APIs use it. Swift callers do not; the compiler calls the Swift implementation, and may inline it. - **`dynamic`** changes how every access is dispatched. The Swift book states that access to a `dynamic` member is always dynamically dispatched using the Objective-C runtime and is never inlined or devirtualized. The detailed cost of each dispatch kind belongs to the material on method call mechanisms. - Together, **`@objc dynamic`** means that a Swift assignment is also a message send, so it reaches the replaced setter and the observer fires. ## The compiler's warning When the key path passed to `observe(_:options:changeHandler:)` names a property that is not `@objc dynamic`, Swift 6.4 warns: "passing reference to non-'@objc dynamic' property 'bytesSent' to KVO method 'observe(_:options:changeHandler:)' may lead to unexpected behavior or runtime trap". Treat it as an error in review. ## `dynamic` without `@objc` Swift 3 inferred `@objc` from `dynamic`; SE-0160 removed that in Swift 4, and the proposal and the Swift book still say a `dynamic` member must be `@objc`. The Swift 6.4 compiler, however, accepts `dynamic` alone on a member of a plain Swift class or an `NSObject` subclass. Such a member gets **no Objective-C entry point** (`responds(to:)` returns `false` for it), so it does nothing for KVO. Always write both words. ## Where else `@objc dynamic` matters 1. **Replacing an implementation through the Objective-C runtime**, for example with `class_replaceMethod` (method swizzling). Without `dynamic`, Swift callers keep calling the original body directly. 2. **Core Data's `@NSManaged` properties**, which are already implemented dynamically by the framework and infer `@objc`. 3. **Bindings or Objective-C code that observes Swift models** during a migration, the usual reason a mixed app still needs KVO. ## Fixing a half-working observer 1. Find the observed property's declaration and check that the class inherits from `NSObject`, since KVO is an `NSObject` facility. 2. Write `@objc dynamic` on the property, not only `@objc`, and not `dynamic` alone. 3. Rebuild and clear every "non-'@objc dynamic' property" warning; each one marks an observer that can silently miss Swift writes. 4. Exercise the property from both sides in a test: assign it in Swift, set it from Objective-C or with `setValue(_:forKey:)`, and assert that the observer ran each time. ## Choosing deliberately - Mark only the properties someone observes; every `dynamic` access gives up inlining and pays for a message send. - `final` does not conflict with `@objc dynamic` for observation: KVO's replacement happens in the Objective-C runtime, outside Swift's class model, and the `final` class in the example notifies. - For Swift-only observers, a `didSet` observer, a callback or an observation mechanism that does not depend on the Objective-C runtime avoids the cost entirely. - Keep the `NSKeyValueObservation` token returned by `observe(_:options:changeHandler:)` alive; observation stops when it is released.

  • Does making the observed class final break KVO on its @objc dynamic properties?
    No. `final` stops Swift subclasses from overriding members; KVO's setter replacement is created at run time by the Objective-C runtime, outside Swift's class model. With `@objc dynamic`, accesses still go through Objective-C messaging, so observation works on a `final` class, as the example's `UploadJob` shows.
  • Why does setValue(_:forKey:) notify for a property that is only @objc?
    `setValue(_:forKey:)` is Foundation's string-keyed setter. It looks the property up by name and sends the setter message through the Objective-C runtime, so it reaches the replaced setter even though Swift's direct assignment does not. That is also why such a bug often hides in testing: some code paths notify and some do not.

  • @objc alone is enough for Swift assignments to trigger KVO.
  • dynamic on its own exposes a member to Objective-C.
  • KVO observes stored property memory, so dispatch is irrelevant.
  • The non-'@objc dynamic' KVO warning is harmless noise.
  • A final class can never be observed with KVO.