365Cocoa

A snippet of Objective-C code per day, 365 days long.
Written by Pieter Omvlee, developer and owner of Bohemian Coding.

May 11

Day 51: KVO+Blocks

Today’s code is not mine, but I do find it incredibly useful. As readers of this blog will know by know, in 10.6 Apple introduced Blocks to Objective-C. I have given plenty examples in the past, but today’s is a favourite of mine.

Andy Matuschak released this code almost a year ago and it’s an incredibly handy way to do Key-Value-Observing (KVO) with Blocks instead of those ugly callbacks. Gone is the need to override obserValueForKeyPath: with a big switch statement to check for the keypaths. This is so much easier:

[self addObserverForKeyPath:@"..." task:^(id obj, NSDictionary *change){
  //...
}];

The source code is hosted on GitHub and you also might want to read Andy’s post for some more info.