I understand that it marks the end of a set of varargs, but why can\'t it be implemented in such a way that doesn\'t require the nil?
The simple reason is that behind the scene it's a for-loop that will continue to take arguments, from the va_list
till it reaches nil
. So the end condition could have been anything, for example the string "stop". But nil
is actually quite smart.
Let's say we have three objects hansel
, gretel
and woodcutter
and create an array of them:
NSArray *startCharacters = [NSArray arrayWithObjects:hansel, gretel, woodcutter, nil];
Now, we realize that woodcutter
never was initiated, so it's nil
, but startCharacters
will still be created with the hansel
and gretel
objects, since when it's reaches woodcutter
it terminates. So the nil-termination in arrayWithObjects:
prevents the app from crashing.
If you don't like to write out nil
you could always create an array like this:
NSArray *startCharacters = @[hansel, gretel, woodcutter];
It's valid, it's shorter, but it will crash if an object is nil
. So the conclusion is that arrayWithObjects:
can still be very useful and you can use it to your advantage.