2

Possible Duplicate:
Why do parameter lists in certain cocoa methods end with a nil?

when I define such methods, I have to put a nil/NULL/0 to indicate the end of those variable arguments, how is stringWithFormat: implemented so that is don't need do so?

Community
  • 1
  • 1
CarmeloS
  • 7,868
  • 8
  • 56
  • 103
  • 1
    I don't know Objective-C, but it might be that the number of arguments can be determined from the format string. – Ry- Apr 08 '12 at 02:56
  • 1
    Duplicates: [NSArray arrayWithObjects needs nil at the end, NSString stringWithFormat and NSLog() doesn't. Why?](http://stackoverflow.com/questions/9971021/nsarray-arraywithobjects-needs-nil-at-the-end-nsstring-stringwithformat-and-nsl) and [Why do parameter lists in certain cocoa methods end with a nil?](http://stackoverflow.com/questions/2477985/why-do-parameter-lists-in-certain-cocoa-methods-end-with-a-nil) – Kurt Revis Apr 08 '12 at 05:14

1 Answers1

11

Because stringWithFormat: uses the format itself to figure out how many arguments it needs.

There are two basic ways to do it (handle variable argument lists).

First is to be told in advance how many arguments there are, either a length or something like a format string. Examples of this is:

int arr[] = {6, 3, 1, 4, 1, 5, 9};
//           ^
//           |
//           +--- number of elements following.

or:

NSString *message = [NSString stringWithFormat: @"Your age is %d", age];
//                                                            ^
//                                                            |
//                                 only one format element ---+

Second is a sentinel value, such as your nil/NULL/0 at the end:

int arr[] = {3, 1, 4, 1, 5, 9, -1};
//                              ^
//                              |
//         marks end of data ---+

Now, obviously, the sentinel method only works if you can distinguish between real data and the sentinel value (easy in the above case since the digits of PI are all positive numbers between 0 and 9 inclusive).

Technically, I guess you could combine them as well (such as a count of groups with each group having a sentinel value), but I've not seen that used in the wild very often.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • 1
    The name of the method is `stringWithFormat:`, the colon is very important, because it indicates that the method takes arguments. – dreamlax Apr 08 '12 at 03:19
  • @dreamlax, point taken, I simply copied what the question had but I've changed it to the colon version now. – paxdiablo Apr 08 '12 at 03:27