Variable arguments in Cocoa
Variable Arguments
If you’ve been using Cocoa for more than five minutes you’ve almost certainly come across a function which takes variable arguments and you might not have even realised it. Variable arguments are used in two very common function calls within Cocoa namely stringWithFormat and arrayWithObjects.
These two function also demonstrate the two manners in which to take variable arguments, Format strings and Nil terminated lists.
Format Strings
NSString *aString = [NSString stringWithFormat:@"string: %@ , number %d, @"string", 123];
The stringWithFormat method is then declared as follows:
+ (id)stringWithFormat:(NSString *)format, ...;
Nil terminated lists
NSArray *myArray = [NSArray arrayWithObjects:@"One", @"Two", @"Three", nil];
The last object of the list in these calls must be nil.
How to implement Variable Arguments
So that’s great and all but how do we accept variable arguments in our functions you ask. The simplest method always being the best the answer here requires using the standard c va_* syntax and a handy Cocoa macro named NS_REQUIRES_NIL_TERMINATION whch tells the compiler that invocations of this method must include a nil-terminated list of arguments.
So the va_* syntax gives us
- va_list - A pointer to a list of arguments.
- va_arg - Retrieves the next argument, must supply type in order to recieve the correct number of bytes
- va_start - Initializes the va_list pointer to point the first argument (after the specified argument).
- va_end - Releases memory held by the va_list structure.
So our function will look something like this,
- (void)appendStringsToString:(NSString *)stringArg, ...{
NSMutableString *newString = [NSMutableString string];
//create the pointer to the list of args
va_list args;
//set the starting point
va_start(args, stringArg);
//loop over the args appending them to the string
//note we are specifying NSString * in the call to va_arg
for (NSString *arg = firstArg; arg != nil; arg = va_arg(args, NSString*)){
[newString appendString:arg];
}
//be good and clean up
va_end(args);
[contents autorelease];
contents = [newContentString retain];
}
And the declaration will look something like this
(void)setContentByAppendingStrings:(NSString *)firstString, ... NS_REQUIRES_NIL_TERMINATION;
And there we have it you can now go ahead and build your functions to take argument lists a handy utility.
Similar Posts
- None Found
One Response to “Variable arguments in Cocoa”
Leave a Reply















Mike on June 23rd, 2009
Thank you so much, not only did I need to learn about variable parameter lists…but I needed a method to append strings!