Methods and optional parameters
ios, objective-c
Solution
The type of method you are describing is called a variadic method. Examples in Cocoa include `+[NSArray arrayWithObjects:]` and `+[NSDictionary dictionaryWithObjectsAndKeys:]`. You access the arguments of a variadic method (or function) using the macros defined in `stdarg.h`.
Here's an example of how the `+[NSArray arrayWithObjects:]` method might be implemented:
+ (NSArray *)arrayWithObjects:(id)firstObject, ... {
int count = 0;
va_list ap;
va_start(ap, firstObject);
id object = firstObject;
while (object) {
++count;
object = va_arg(ap, id);
}
va_end(ap);
id objects[count];
va_start(ap, firstObject);
object = firstObject;
for (int i = 0; i < count; ++i) {
objects[i] = object;
object = va_arg(ap, id);
}
va_end(ap);
return [self arrayWithObjects:objects count:count];
}
Problem
I have read in the Apple Documentation that we can use optional parameters in objective c methods call. Example from the Apple documentation : 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]; ``` Can someone tell when to use this feature and how ? is there any example in the Apple API ? thanks