Variable arguments in Objective-C methods

Q: How can I write a method that takes a variable number of arguments, like NSString’s +stringWithFormat:?

A: Methods that take variable arguments are known as variadic methods.

Keep in mind that the implementation of an Objective-C method is just a block of code, like a C function. The variadic argument macros described in the stdarg(3) manual page work the same way in a method as they do in an ordinary function.

Here’s an example of an Objective-C category, containing a variadic method that appends all the objects in a nil-terminated list of arguments to an NSMutableArray instance:

Listing 1: A typical variadic method.

#import <Cocoa/Cocoa.h>

@interface NSMutableArray (variadicMethodExample)

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

@end

@implementation NSMutableArray (variadicMethodExample)

- (void) appendObjects:(id) firstObject, ...
{
id eachObject;
va_list argumentList;
if (firstObject)                      // The first argument isn't part of the varargs list,
  {                                   // so we'll handle it separately.
  [self addObject: firstObject];
  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);
  }
}

@end

 

Tagged: , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: