365Cocoa

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

Mar 7

Day 9: -each:

In yesterday’s post I introduced the +drawImageWithSize:block: method and said I wasn’t reall happy with the name but couldn’t think of a better one. @uliwitness was kind enough suggest a better name for this method; drawToImageWithSize:usingBlock: and I think he’s right. He also pointed out a glaring omission to this site which is of course the fact that it’s impossible to leave a comment. So as of today I believe you actually leave a comment, and I greatly encourage you to do so.

As you might have guessed by know, I’m a big fan of blocks and I use them a lot. Apple was kind enough to add some handy methods on existing foundation classes such as NSArray but they’ve really gone out of their way to make them as long as possible: - (void)enumerateObjectsUsingBlock:(void (^)(id obj, NSUInteger idx, BOOL *stop))block. I fully understand the argument for long method names but comparing this with Ruby’s 4-character long each method makes me frown a bit. Apart from that, 9 out of 10 I don’t need the index argument and I don’t need to stop the array. Enough motivation I should think for a shorter version:

- (void)each:(void (^)(id object))block
{
  [self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    block(obj);
  }];
}

Apple’s provided another enumeration-function that can do the enumeration concurrently. Needless to say this can be extremely handy at times but again I just find the method too long and so I wrote an -eachConcurrent: method which I’ll leave as an exercise to the reader. ;-)