The Importance of nil

Take a look at these two nearly-identical pieces of code. Can you spot the difference?

UIActionSheet *actionSheet = [[UIActionSheet alloc]
initWithTitle:@”Choose Image Source”
delegate:self
cancelButtonTitle:@”Cancel”
destructiveButtonTitle:nil
otherButtonTitles:@”Camera”, @”Photo Library”];

UIActionSheet *actionSheet = [[UIActionSheet alloc]
initWithTitle:@”Choose Image Source”
delegate:self
cancelButtonTitle:@”Cancel”
destructiveButtonTitle:nil
otherButtonTitles:@”Camera”, @”Photo Library”, nil];

The first one will cause you untold amounts of misery as you futilely search with increasing desperation as the hours go by for the mysterious cause of your app’s sudden propensity to hang when a certain button is pressed. The second one has a “nil” at the end.

(The moral of the story is that variable length arguments need to be terminated with “nil”. Also, don’t program while sleepy.)

3 Responses to “The Importance of nil”

  1. Si Brindley Says:

    That’s a handy tip. Hope I remember it!

  2. Si Brindley Says:

    Thinking about it, this is something the compiler ought to be able to check for. I realise it’s a runtime error, not a syntax error…but if the compiler knows the API then it *could* catch this error.

  3. Mach Says:

    Ah, but this gets insidious if the last argument is a variable. How is the compiler going to know if the value is nil or not? In fact, this can be a problem with a similar method for NSDictionary, “dictionaryWithObjectsAndKeys”:

    http://www.hwaethwugu.com/blog/archives/2007/04/14/nsdictionary_dictionarywithobjectsandkeys_considered_harmful