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.

2
  • 1
    Because it doesn't know how. It's a standard variable-length parm list, and there must be some sort of count or end marker for the length to be known. Commented Apr 15, 2012 at 20:33
  • It can be done with a macro, but other than that, what @HotLicks said is correct. Commented Apr 15, 2012 at 20:44

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Such a compiler extension is coming! Hallelujah!
there is no way that arrayWithObjects adds the hello and the world, and then adds the nil?
@動靜能量: 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.
@IuliusCæsar yes - good news, indeed :)
@動靜能量 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).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.