The initWithObjects:
method of NSArray
takes an indefinite list of arguments:
NSMutableArray *array = [[NSMutableArray alloc]initWithObjects:(id), ..., nil
How can I define my own method like this?
- (void)CustomMethod:????? <= want to take infinite arguments {
}
The "infinite arguments" are variable arguments and the methods that use them are called variadic methods. You define them the same way as your NSMutableArray
example. Apple's Technical Q&A has an example of how to implement it.
- (void) appendObjects:(id) firstObject, ...
{
id eachObject;
va_list argumentList;
if (firstObject) // The first argument isn't part of the varargs list,
{ // so we'll handle it separately.
[self addObject: firstObject];
va_start(argumentList, firstObject); // Start scanning for arguments after firstObject.
while ((eachObject = va_arg(argumentList, id))) // As many times as we can get an argument of type "id"
[self addObject: eachObject]; // that isn't nil, add it to self's contents.
va_end(argumentList);
}
}
The reason for the nil
argument is so that you know when you have reached the end of the list. Functions like NSLog
and printf
do not require the last argument to be nil
because it can count the number of specifiers in the format string (%d
, %s
etc...)
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