0

Possible Duplicate:
Why does NSArray arrayWithObjects require a terminating nil?

It is said that we need to always use a nil as the last item for arrayWithObjects:

NSArray *wordList = [NSArray arrayWithObjects: @"hello", @"world", nil];

Why can't arrayWithObjects not require the nil and just add the nil for us. Some forum said that's because the nil act as a sentinel for other methods... but isn't that an implementation issue that shouldn't concern the user of the class?

For example, if other languages require

 list = [1 ,2, nil]    # Ruby

to build an array, it can be somewhat weird.

Community
  • 1
  • 1
nonopolarity
  • 146,324
  • 131
  • 460
  • 740

1 Answers1

1

Because the automatic nil insertion would require some language or compiler extension.

In the case of the variadic list, the terminator's required for the implementation to know when to stop reading.

Fortunately, your compiler supports sentinel attributes, so this should not be a problem if you turn up and pay attention to your compiler warnings.

justin
  • 104,054
  • 14
  • 179
  • 226
  • Such a compiler extension is [coming](http://stackoverflow.com/questions/9693647/is-there-some-literal-dictionary-or-array-syntax-in-objective-c)! Hallelujah! – jscs Apr 15 '12 at 20:40
  • there is no way that `arrayWithObjects` adds the `hello` and the `world`, and then adds the `nil`? – nonopolarity Apr 15 '12 at 20:41
  • @動靜能量: The `nil` isn't part of the array; it's used to find the end of the list of arguments. The method itself can't know how many arguments it got. – jscs Apr 15 '12 at 20:44
  • @IuliusCæsar yes - good news, indeed :) – justin Apr 15 '12 at 20:47
  • @動靜能量 well, you could create some convenience methods/functions, if that's actually useful for your case (approximately as complex to write, but enhanced checking would be available). – justin Apr 15 '12 at 20:52