|
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
See the stdarg(3) manual page for the full documentation of the Document Revision History
Posted: 2005-01-13 |
|