2

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

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

What is the purpose of the nil?

jscs
  • 63,694
  • 13
  • 151
  • 195
Yarin
  • 173,523
  • 149
  • 402
  • 512

2 Answers2

4

Null terminated variable argument lists, or va_lists, keep walking the list of arguments until they encounter 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.

jscs
  • 63,694
  • 13
  • 151
  • 195
Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320
  • 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. – Amy Worrall Aug 30 '10 at 16:54
  • Exactly. Since the `printf` function **knows** how many args to expect, you don't need null termination. – Jacob Relkin Aug 30 '10 at 16:55
  • 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 Aug 30 '10 at 19:38
  • Note that my comment is entirely orthogonal to Jacob's correct answer. More directed at @Amorya. – bbum Aug 30 '10 at 19:38
1

To mark the end of the list of objects.

Here's a discussion from CocoaBuilder.

Abizern
  • 146,289
  • 39
  • 203
  • 257