Using the Context Pointer Defensively

In order for any class to observe key-value changes, it must implement the observeValueForKeyPath(_:ofObject:change:context:) method; it is not possible to provide a different method to KVO. Consequently, it is possible to mistakenly intercept notifications intended for a superclass.

Consider the case of some class Maple, which is a subclass of some other class Tree. Both classes observe Environment’s key path season independently. Unless the developer takes precautions, Maple will receive its key-value-observing messages and those intended for Tree, because Maple has effectively overridden Tree’s KVO method. To fix this, Maple must correctly distinguish between KVO notifications intended for it ...

Get Cocoa Programming for OS X: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.