24/7 twenty-four seven

iOS/OS X application programing topics.

Objective-C における可変引数の実装方法

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.

Mac Developer Library
#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