Key-Value Observing
Ask anyone who’s been around the NSBlock a few times: Key-Value Observing has the worst API in all of Cocoa. It’s awkward, verbose, and confusing. And worst of all, its terrible API belies one of the most compelling features of the framework.
→ nshipster.com/key-value-observing/
Key-Value Observing (KVO) has an ugly, wordy API, but it is one of Cocoa’s most powerful features.
It lets any object watch properties of any other object and receive automatic notifications when they change. Almost every NSObject subclass supports it without extra work.
Best ways to use it well:
- Always pass a unique static context pointer to tell your own observations apart.
- Use the selector-to-string trick for key paths so typos are caught at compile time.
- Remove observers carefully (often in dealloc) and guard against double removal.
- For calculated properties, declare which keys affect them so changes trigger correctly.
Despite the rough edges, KVO keeps complex apps in sync with very little code.
Category:
Tags:
Year: