365Cocoa

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

May 12

Day 52: changeKeys:inBlock:

If for some reason you’re writing your own getters and setters code, you want to comply to KVO and properly notify any observers of change using willChangeValueForKey: and didChangeValueForKey:. Now this is straightforward enough but starts to get really ugly if in one method you have to notify a change to several keys using first having lets say four willChangeValueForKey: and afterwards again four didChangeValueForKey: is particularly ugly. Especially if you do this in few locations.

This is the soluton I came up with. I also wrote one for just one key but that one is too trivial to mention here separately

- (void)changeKeys:(NSArray *)keys inBlock:(BLOCK)block
{
  for (NSString *key in keys)
    [self willChangeValueForKey:key];
  block();
  for (NSString *key in keys)
    [self didChangeValueForKey:key];
}

  1. 365cocoa posted this