Declare a method like this in @interface
:
- (id)myObjectWithObjects:(id)firstObject, ... NS_REQUIRES_NIL_TERMINATION;
Then in @implementation
you define it like this:
- (id)myObjectWithObjects:(id)firstObject, ... { va_list args; va_start(args, firstObject); for (id arg = firstObject; arg != nil; arg = va_arg(args, id)) {
va_list
, va_start
, va_arg
and va_end
are the standard C syntax for handling variables. Describing them is simple:
va_list
is a pointer to a list of variable arguments.va_start
- Initializes va_list to indicate the first argument after the specified argument.va_arg
- Displays the next argument from the list. You must specify the type of the argument (so va_arg knows how many bytes to retrieve).va_end
- frees memory stored in the va_list data structure.
Read this article for a better explanation - Variable Argument Lists in Cocoa
See also: "IEEE Std 1003.1 stdarg.h"
Another example from Apple Technical Q & A QA1405 is variable arguments in Objective-C methods :
@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 contents. va_end(argumentList); } } @end
chown source share