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?

2 Answers 2

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.

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

4 Comments

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.
Exactly. Since the printf function knows how many args to expect, you don't need null termination.
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.
Note that my comment is entirely orthogonal to Jacob's correct answer. More directed at @Amorya.
1

To mark the end of the list of objects.

Here's a discussion from CocoaBuilder.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.