Methods that accept a variable number of parameters
It’s very common in Cocoa to find methods that take a variable number of parameters (ending in nil). For example, see NSArray’s arrayWithObjects: or dictionaryWithObjectsAndKeys: in NSDictionary.
In both cases, the method will loop through our list processing each element until it reaches the nil.
How to create our own variadic methods in Objective C
The plumbing necessary for variadic methods is not Objective C specific, but rather “inherited” form the older C substrate. Usage of variadic functions is very common in C (see printf) and is described in the The Bible according to Kernighan & Ritchie. It’s on chapter 7 of my copy of “The C Programming Language” (in Spanish).
Creating a variadic method in Objective C is similar to creating a variadic function in C as described by Kernighan & Ritchie.
To create a variadic method, you must first define at least a single parameter. This will always work, even for empty lists, as you’ll never forget to provide the ending nil.
Therefore, even empty lists will consist in at least one element: nil.
Within your method, you need to define a variable with type va_list that represents a pointer to the first element of the list of parameters. You will also need to call the va_start macro. This will initialize your va_list so it points to the first element.
While you process the elements of the list, you must call va_args to obtain a pointer to the next element.
Once finished, call va_end for cleanup.
Example of variadic method in Objective C
A simple method that takes a variable sized list of strings (NSString) and returns the number of strings it received:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
-(int) countWords: (NSString *)firstWord, ...{ va_list words; // Lista de palabras va_start(words, firstWord); // Points to the first element int i = 0; NSString * word; for (word = firstWord; word; word = va_arg(words, NSString*), i++) { NSLog(@"#%d: %@", i, word); } va_end(words); return ++i; } |






Nice article. Actually, variable list of parameters was first implemented in plain C language from which Objective C has inherited this feature. On C language, you need to include stdarg.h header in order to have va_start, va_arg and va_end macros defined.
One important thing to notice is that: variable lists of parameters MUST have at least one fixed argument. This is necessary in order to ensure that va_start macro can mark the beginning of the stack in order to have va_arg macro safely calculate the position of each element, avoiding invalid memory accesses.
Muito obrigado pelo comentario, Ronaldo!
[...] is a variadic method that accepts a list of strings of variable length. The list must end with [...]
[...] How To Display Transparent Modal ViewControllers Variadic methods in Objective C [...]