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
        [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.


Posted on November 29, 2011, in Code, Tips and tagged , , , . Bookmark the permalink. 2 Comments.

  1. A slight improvement on this: You should make your static void pointers const, since they shouldn’t be changeable inside your class implementation.

    e.g.: static void *const p = (void *)&p;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: