KVC and KVO

Platform & distribution Mid-level Swift 5.0+ iOS 17+ Reviewed By Alok Singh

Pick the fix

You need to know when an AVPlayerItem becomes ready to play. Best approach?

Options
Hint 1 of 1

KVO returns a token.

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A Store item.observe(\.status, options: [.new]) { item, _ in … } in a property

Correct. That's the block KVO API, and the stored token keeps it alive.

Why not the others?
  • B Use didSet on item.status. You can't add observers to another type's property.
  • C Poll item.status with a Timer. It's wasteful and laggy.
  • D Call observe and ignore the return value. The observation ends immediately.

30-second answer

Key-Value Coding reads and writes properties by string key on NSObject subclasses. Key-Value Observing notifies you when an observable property changes. In Swift, KVO requires an NSObject subclass with @objc dynamic properties, and you use the block API observe(\.property, options:), which returns an NSKeyValueObservation you must keep. It is still useful for Apple types like AVPlayerItem.status.

Practise saying it · 30 s. No recording, just a timer

Explain KVC and KVO.

Say your answer out loud, then check which of these points you covered:

  • String-key access
  • @objc dynamic
  • Keep the token
  • Use for Apple types

Deep dive

The observation stops when the token is released.

Swift key paths give type safety over string keys.

For your own Swift types, prefer Observation or Combine.

Observers may be called on the thread where the change happened.

Common mistakes

  • KVO on plain Swift properties.
  • Discarding the observation token.

Senior take & follow-ups

Seniors use KVO only where Apple APIs need it.

Follow-up questions

Think of your answer first, then open the hint.

  1. Why is my KVO callback never called?

    Show hint

    The token was released, or the property isn't @objc dynamic.

  2. Which thread runs the callback?

    Show hint

    The thread that made the change.

Suggest a fix if something here is wrong or out of date.