[ObjectiveC] Variable arguments list

From Apple Q&A QA1405, an easy way to call a method with variable parameters nil-terminated,
like

[code lang=”java” autolinks=”false” collapse=”false” firstline=”1″ gutter=”true” htmlscript=”false” light=”false” padlinenumbers=”false” smarttabs=”true” tabsize=”4″ toolbar=”false”][NSMutableArray arrayWithObjects…, nil][/code]


We use va_start and va_args to read parameters.

[code lang=”java” autolinks=”false” collapse=”false” firstline=”1″ gutter=”true” htmlscript=”false” light=”false” padlinenumbers=”false” smarttabs=”true” tabsize=”4″ toolbar=”false”]- (NSMutableArray*) appendObjects:(id) firstObject, …
{
NSMutableArray *retArray = [NSMutableArray array];id eachObject;
va_list argumentList;
if ( firstObject )
{
[retArray addObject:firstObject];va_start(argumentList, firstObject);
while ( (eachObject = va_arg(argumentList, id)) )
{
[retArray addObject: eachObject];
}
va_end(argumentList);
}

return retArray;
}

– (int) sumNumbers:(int) firstNumber, …
{
int tot = 0;int eachNumber;
va_list argumentList;if ( firstNumber )
{
tot += firstNumber;
va_start(argumentList, firstNumber);
while ( (eachNumber = va_arg(argumentList, int)) )
{
tot += eachNumber;
}
va_end(argumentList);
}
return tot;
}[/code]

You can call method passing an infinite number of parameters in this way:

[code lang=”bash” autolinks=”false” collapse=”false” firstline=”1″ gutter=”true” htmlscript=”false” light=”false” padlinenumbers=”false” smarttabs=”true” tabsize=”4″ toolbar=”false”]NSLog(@"%@", [self appendObjects:@"asd", @"qwe", @"rty", nil] );
NSLog(@"%@", [self appendObjects:@"asd", @"qwe", @"rty", @"fgh", nil] );NSLog(@"%d", [self sumNumbers:5, 5, 5, nil] );
NSLog(@"%d", [self sumNumbers:1, 2, 3, 4, 5, nil] );
NSLog(@"%d", [self sumNumbers:5, 5, 5, 123, 28, 10, 84, nil] );[/code]

Ref: albertopasca.it
Ref: apple q/a

 

Alberto Pasca

Software engineer @ Pirelli & C. S.p.A. with a strong passion for mobile  development, security, and connected things.