Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a method that has many (or infinite) arguments

The initWithObjects: method of NSArray takes an indefinite list of arguments:

NSMutableArray *array = [[NSMutableArray alloc]initWithObjects:(id), ..., nil

How can I define my own method like this?

- (void)CustomMethod:????? <= want to take infinite arguments {

}
like image 689
S.J. Lim Avatar asked Aug 16 '11 14:08

S.J. Lim


1 Answers

The "infinite arguments" are variable arguments and the methods that use them are called variadic methods. You define them the same way as your NSMutableArray example. Apple's Technical Q&A has an example of how to implement it.

- (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);
    }
}

The reason for the nil argument is so that you know when you have reached the end of the list. Functions like NSLog and printf do not require the last argument to be nil because it can count the number of specifiers in the format string (%d, %s etc...)

like image 91
Joe Avatar answered Nov 15 '22 20:11

Joe