Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the 1st argument of an Objective C variadic function mandatory?

Here is an example of a variadic function in Obj C.

// This method takes an object and a variable number of args
- (void) appendObjects:(id) firstObject, ...;

Is it really mandatory to have the first argument as an Obj C object? If not, what should be the syntax?

EDIT: Thanks for your responses - the first argument does not need to be an NSObject, but what I meant to ask is: Is it possible to do away with the first argument altogether? I probably did not frame the question well the first time around; sorry about that

- (void) appendObjects: ...;

The above declaration throws the following error: Expected ';' after method prototype

like image 470
S B Avatar asked Sep 09 '11 06:09

S B


People also ask

What is variadic function in C?

Variadic functions are functions that can take a variable number of arguments. In C programming, a variadic function adds flexibility to the program. It takes one fixed argument and then any number of arguments can be passed.

What symbols are used in a function declaration to indicate that it is a variadic function?

A function with a parameter that is preceded with a set of ellipses ( ... ) is considered a variadic function. The ellipsis means that the parameter provided can be zero, one, or more values.

What is variadic function in Python?

Variadic parameters (Variable Length argument) are Python's solution to that problem. A Variadic Parameter accepts arbitrary arguments and collects them into a data structure without raising an error for unmatched parameters numbers.

What is variadic parameters in Golang?

A variadic function is a function which accepts a variable number of arguments. It can be used when the number of input params are unknown. The code: getNames.go. As we can see the variadic func (getNames() accepts variable number of input values — zero or more.


1 Answers

It doesn't have to be anything really. There are two hidden arguments to every Objective-C method, self, and _cmd (in that order). self is self-explanatory (haha), but a lesser-known one is _cmd, which is simply the selector that was used to invoke the current method. This makes it possible to use variadic arguments with Objective-C methods seemingly without using an initial argument like you do with a standard variadic C function.

- (void) someMethod:...
{
    va_list va;

    va_start(va, _cmd);

    // process all args with va_arg

    va_end(va);
}

Then you can call the method like this:

 [someObj someMethod:1, 2, 3];
like image 111
dreamlax Avatar answered Oct 06 '22 17:10

dreamlax