Blog Archives

A Cool KVO Trick

A coworker of mine attended the Voices that Matter conference in Boston a couple of weeks ago and shared this idea about KVO observing from Mike Ash during his Defensive Programming talk.  He suggests supplying a static pointer to the context parameter:


static void *p = &p;

[someObj addObserver:self forKeyPath:@"aPath" options:NSKeyValueObservingOptionNew context:p];

// ...

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (context == p)
    {
        // do stuff
    }
    else
    {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

Seems like a lot of magic at first, but by specifying a context every time and using one that’s not only unique to your object but also to the file containing your subclass you can ensure that the message sent to you is actually for you and you avoid potentially stepping on the toes of your super class. Neat stuff! It’s also worth noting that checking the context pointer first is a super-fast way to see if you need to care about the observation method.

Side note: if you’re not subscribed to Mike Ash’s Friday Q&A blog (link above), you definitely should. I learn something new there every week.