Make Better Things



I like to make better things.

Variable number of arguments in Objective-C methods

Ever wondered how the NSString’s +stringWithFormat: method work? How you can pass endless arguments in it?

Well methods that take variable arguments are known as variadic methods.

Here is an example of such a method

Declare variable argument function in your .h file as below

- (void) appendObjects:(id) firstObject, ...; // This method takes a nil-terminated list of objects.

Here is the definition in .m file –

- (void) appendObjects:(id) firstObject, ...
{
     id eachObject;
     va_list argumentList;
     if (firstObject) // The first argument isn't part of the varargs list,
     {                                   
           [self addObject: firstObject];// so we'll handle it separately.
           va_start(argumentList, firstObject); // Start scanning for arguments after firstObject.
           while (eachObject = va_arg(argumentList, id)) // As many times as we can get an argument of type "id"
           {
               [self addObject: eachObject]; // that isn't nil, add it to self's contents.
           }
           va_end(argumentList);

     }

}

Category: iPhone, Objective-C

Tagged:

Leave a Reply