Elegant and Robust Cocoa Initializers

xcode.jpg

I was reading NetNewsWire this morning and one of the feeds had this article on the best way to write Cocoa initializers. I have to say that I didn't know it was possible to have the self re-defined in the super's init method. That certainly does change things.

His default initializer code is elegant and robust:

  - init {
      if (self = [super init]) {
          // set up instance variables and whatever else here
      }
      return self;
  }

or, if you're into trapping errors like I often am doing, you have the 'negative' of this method:

  - init {
      BOOL    error = NO;
 
      if (!error) {
          if ((self = [super init]) == nil) {
              // flag the error and log the problem
              error = YES;
              NSLog(...);
          }
      }
 
      return self;
  }

When I looked back at my initializers for a few projects, I was stunned that I have the exact same code as he did. I thought I had forgotten the self could change, but I hadn't! I'm amazed at myself. This is a wonderful little surprise.

If in doubt, read the page, it's full of good reasons for the checks. Hot Dog! I had it. Sweet.