Define a method that has many (or infinite) arguments

The initWithObjects: NSArray accepts an undefined list of arguments:

 NSMutableArray *array = [[NSMutableArray alloc]initWithObjects:(id), ..., nil 

How can I define my own method as follows?

 - (void)CustomMethod:????? <= want to take infinite arguments { } 
+8
syntax objective-c arguments
source share
1 answer

"Infinite arguments" are variable arguments, and the methods they use are called variable methods. You define them just like your NSMutableArray example. Apple Tech Q&A provides 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 contents. va_end(argumentList); } } 

The reason for the nil argument is because you know when you have reached the end of the list. Functions such as NSLog and printf do not require the last argument to be nil , because it could count the number of qualifiers in the format string ( %d , %s , etc.)

+20
source share

All Articles