Saturday, November 28, 2009 [Tweets] [Favorites]

NSError** Is Hard

Bill Bumgarner highlights a non-intuitive part of the NSError contract: it’s not safe to look at an error object unless the method returned failure.

2 Comments

"You must not assume anything about the return-by-reference value of fileError until you check whether or not fileContents was nil. Not ever. Setting fileError to nil prior to calling the pass-error-by-reference method does nothing useful."

I'm worried about a different scenario - where the method returns failure but for whatever reason doesn't set NSError. For that reason I always set NSError to nil. I'm sure I've seen that happen with Apple methods, but don't ask me now to say where and when.

Frankly, there are very few reasons not to set something to nil, especially when you are assuming what some other function, the source code for which you cannot see, might do. You WILL avoid crashes by initializing everything to nil

Yes, I mentioned to Bumgarner that initializing to nil will help if the method returns failure because the receiver was unexpectedly nil.

Stay up-to-date by subscribing to the Comments RSS Feed for this post.

Leave a Comment