From Objective C Programming Guide (Under the "Object Messaging" section),
Methods that take a variable number of parameters are also possible, though they’re somewhat rare. Extra parameters are separated by commas after the end of the method name. (Unlike colons, the commas are not considered part of the name.) In the following example, the imaginary makeGroup: method is passed one required parameter (group) and three parameters that are optional:
[receiver makeGroup:group, memberOne, memberTwo, memberThree];
I tried to create such a method and it shows an error
"Expected ';' after method prototype"
when I try to declare the below function in my interface file(.h file).
- (void) printMyClass: (int) x, (int) y, (int) z;
Can anyone give sample example to create such a method like makeGroup
Thank you
The number of parameters can be varied; parameters – a name that corresponds to an array of parameters. 2. What are the advantages of using variable number of arguments in methods? Using a variable number of arguments gives the following advantages: you can pass a different number of arguments to the same method.
The general form of a method declaration with a variable number of arguments is: return_type MethodName ( params type [] parameters ) { // ... } type – the type of parameters that the method receives. The number of parameters can be varied; parameters – a name that corresponds to an array of parameters. 2.
Objective-C Variables. A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in Objective-C has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.
Variable number of arguments in C++. Sometimes, you may come across a situation, when you want to have a function, which can take variable number of arguments, i.e., parameters, instead of predefined number of parameters.
You can see this link.
In your header file define the methods with three dots at the end
-(void)yourMethods:(id)string1,...;
And in you implementation file write the methods body
-(void)yourMethods:(id)string1, ...{
NSMutableArray *arguments=[[NSMutableArray alloc]initWithArray:nil];
id eachObject;
va_list argumentList;
if (string1)
{
[arguments addObject: string1];
va_start(argumentList, string1);
while ((eachObject = va_arg(argumentList, id)))
{
[arguments addObject: eachObject];
}
va_end(argumentList);
}
NSLog(@"%@",arguments);
}
Now call your method
[self yourMethods:@"ab",@"cd",@"ef",@"gf",nil];
NOTE: remember to put nil at the end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With