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


A roundup of my favorite iOS and Cocoa blogs

These are some of the better blogs and authors in my Google Reader related to iOS, Cocoa, and Objective-c:

“iPhone Development” – Jeff LaMarche : Always well written and in depth articles. Virtually every article gets starred in Google Reader.
“Cocoa with Love” – Matt Gallagher : If you’re looking for how to use an obscure part of the apple frameworks, this would be the first place to look. Usually Matt’s posts come with accompanying sample code.
“Able Pear Software” : A lot of good beginner articles. Not updated as frequently as it used to be, but their twitter feed has been very active with links to resources.
“Dr. Touch” : Another resource for finding information on lower level or more obscure cocoa tips.
Cocoa Is My Girlfriend” : Real world coding examples
“iCodeBlog” : Tips and help from a variety of authors