How can I pass variable number of arguments to method2 from method1 that takes a variable number of arguments?

arguments, objective-c

Solution

No, in C (and Objective-C), it is not possible to pass down variadic arguments.

The idiomatic solution is to get yourself an initializer that takes a `va_list`, make that as the designated initializer, and then call it from every other method. From within a variadic method, this would look like:

- (instancetype)initWithVarargs:(id)first, ...
{
    va_list args;
    va_start(args, first);
    id obj = [self initWithFirst:first VAList:args];
    va_end(args);
    return obj;
}

and here's a designated initializer that takes a `va_list` argument:

- (id)initWithFirst:(id)first VAList:(va_list)args
{
    id obj;
    while ((obj = va_arg(args, id)) != nil) {
        // do actual stuff
    }
    // the return self, etc.
}

j

Problem

Assume that we have methods: ``` -(instancetype) initWithElements:(id)firstElement, ... NS_REQUIRES_NIL_TERMINATION; +(instancetype) objWithElements:(id)firstElement, ... NS_REQUIRES_NIL_TERMINATION; ``` I understand, how to work with variable number of arguments in `-initWithElements:`, but I don't understand how to pass variables from `-objWithElements:` to `-initWithElements:`. I mean, I want to write something like: ``` +(instancetype) objWithElements:(id)firstElement, ... NS_REQUIRES_NIL_TERMINATION { return [[[self] initWithElements:ELEMENTS] autorelease]; } ``` Is it even possible? The only solution for my problem I see is to store arguments in array and use helper method that will init object with given array.

Original source