views:

46

answers:

2
myArray = [NSArray arrayWithObjects:aDate, aValue, aString, nil];

This array convenience method takes a comma-separated list of objects ending with nil.

What is the purpose of the nil?

+3  A: 

Null terminated variable argument lists, or valists, keep walking the list of arguments until it encounters a placeholder or sentinel, which is nil.

Since the method has no way of knowing how many arguments you are passing, it needs the sentinel (nil) to tell where the list ends.

Jacob Relkin
To follow up on that: if you somehow know exactly how many arguments the user is going to pass in (such as in NSLog, where you can count the % signs in the first string to find out), you don't need a nil as you can just read as many arguments as you're expecting. But if there's no way of the method knowing, as in your NSArray example, then there has to be something to mark the end of the list.
Amorya
Exactly. Since the `printf` function **knows** how many args to expect, you don't need null termination.
Jacob Relkin
Actually, you can't necessarily count the # of arguments by counting the %s in a format string. There are format permutations that consume multiple arguments. Note also that the rules for packing arguments into a vararg frame vary considerably per argument type and architecture. Decoding 'em is hard.
bbum
Note that my comment is entirely orthogonal to Jacob's correct answer. More directed at @Amorya.
bbum
A: 

To mark the end of the list of objects.

Here's a discussion from CocoaBuilder.

Abizern