If you define a method, add a comma and three points after the last formal parameter (,... ), it indicates that the parameter can accept multiple argument values.
To get a variable number of parameters in a program, you need to use the following keywords
· Va_list: This is a type that defines a pointer variable that points to a mutable argument list
· Va_start: This is a function that specifies that a list of deformable parameters is to be processed and that the pointer variable points to the first parameter of the deformable parameter list
· Va_end: End processing of deformable parameters, releasing pointer variables
· Va_arg: This function returns the value of the parameter currently pointed to by the pointer and moves the pointer to the next parameter
Example
Varargs.h
#import <Foundation/Foundation.h>@interface varargs:nsobject// Method defining the variable number of parameters-(void) Test: (NSString *) name,...; @end
Varargs.m
#import "Varargs.h"@implementationVarargs-(void) Test: (NSString *) name,... { //use Va_list to define a arglist pointer variable that points to the mutable argument listva_list argList; //if the first name parameter is present, then the following arguments need to be processed if(name) {//because the name parameter is not in the mutable argument list, the name parameter is processed firstNSLog (@"%@", name); //let ArgList point to the first parameter of the first mutable argument list, start extracting the parameters of the mutable argument listVa_start (argList, name); //Va_arg is used to extract the parameters currently pointed to by the arglist pointer and move the pointer to the next parameter//The arg variable is used to hold the currently acquired parameter, and if the parameter is not nil, enter the loop bodynsstring* arg = Va_arg (argList,ID); while(ARG) {//print out each parameter.NSLog (@"%@", ARG); //extract the next parameter again, and move the pointer to the next parameterarg = Va_arg (argList,ID); } //release arglist pointer, end extractva_end (argList); }}@end
Main function
int Main (int argc, const char * argv[]) {@autoreleasepool { Varargs * va = [[Varargs alloc] init]; [VA test: @ " crazy iOS handout " , @ " crazy Android Handout , @" crazy Ajax Handout nil]; return 0 ;}
Note: A variable number of parameters can only be at the end of the formal parameter list. The most grace of a method gives you a variable length parameter.
From "Crazy iOS Handouts" (top)