Why do argument list in some methods end with nil? I have noticed this particularly in the collection classes, for example NSSet:
mySet = [NSSet setWithObjects:someData, aValue, aString, nil];
and NSArray:
NSArray *objects = [NSArray arrayWithObjects:@"value1", @"value2", @"value3", nil];
It has to do with how variable argument lists work (
va_list, seen as...in the parameters). When the code is trying to extract all of the values in the list, it needs to know when to stop (because it doesn’t know how many there are). We denote the end of the list with a special value called a “sentinel”, which is usuallyNULL. That way, when the processing code comes across anilin theva_list, it knows that it’s reached the end. If you leave out thenil, you’ll get strange errors, because the code will just keep on reading down the stack, interpreting things as objects, until it finds anil.This is very similar to why C strings have to be
NULL-terminated.As a side note, the
stringWithFormat:and similarprintf-style methods don’t need a sentinel, because it figures out how many parameters it needs based on how many%modifiers are in the format string. So if you give a format string of@"hello, %@", then it will only look for one extra argument, because there is only one % modifier.