Macros for more sane NSError programming

Jeff Johnson recently posted an entry about using NSError in Cocoa to dramatically improve error handling. I wholeheartedly agree with the idea, and in fact adding NSError “variants” during MPQKit’s refactor was one of my top priorities.

That being said, there are a few annoyances with using NSError, one of which is constantly having to check if the NSError ** variable your method was given isn’t nil before you dereference it to assign it a new NSError object. There’s also the verbosity of creating those instances.

So in order to make my life a little bit easier, I wrote a set of macros that cover the specific case where you want to create an NSError instance and then bail out of the method. They check if the NSError ** is nil or not, create an NSError instance and assign it to the reference (or set the reference to nil for the no error ones), then return a provided value to the caller. It’s important to note that you shouldn’t use a semi-colon after them, since the macros expand to a block ({…}). This is necessary for the macros to work correctly in situations such as if statements.

You can download the header file from the MPQKit Trac wiki. There are no license restrictions whatsoever.