Implementation of optional parameters in Objective-C
In Objective-C, multiple APIs are available for optional parameters, for example:
- (instancetype)initWithFormat:(NSString *)format, ...;
- (instancetype)initWithTitle:(NSString *)title message:(NSString *)message delegate:(id /*
*/)delegate cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ...;
Sometimes we also need to write variable parameters, such as network request passing variable parameters, and database operation performing variable parameter query.
Define a Man class. There is a way to cook a big meal.
// Initialize and define the method @ interface Man: NSObject-(NSString *) makeMilk :( NSString *) milk fruit :( NSString *) fruit food :( NSString *) food ,...; @ end
The syntax of a variable parameter is that the preceding parameter is a fixed parameter, and the last parameter is a variable parameter. The type of the variable parameter is the same, and the last parameter ends with a comma and a ellipsis.
This method has two parameters (milk and fruit) that are fixed, and the following food can be long or short, depending on the situation.
-(NSString *) makeMilk :( NSString *) milk fruit :( NSString *) fruit food :( NSString *) food ,...; {NSMutableArray * arr = [[NSMutableArray alloc] init]; va_list params; // defines a pointer to a variable number of parameter lists; id argument; if (food) {// point the parameter list pointer arg_ptr to the first optional parameter in the function parameter list. Note: argN is a fixed parameter located before the first optional parameter (or, the last fixed parameter;... The order of parameters in the function parameter list in the memory is the same as that in the function declaration. If the declaration of a va function is void va_test (char a, char B, char c ,...), Then its fixed parameters are a, B, c in sequence, and the last fixed parameter argN is c, so it is va_start (arg_ptr, c ). Va_start (params, food); while (argument = va_arg (params, id) {// return the parameter indicated by the arg_ptr pointer in the parameter list. The return type is type, and the pointer arg_ptr points to the next parameter [arr addObject: argument];} va_end (params); // releases the list pointer} return [NSString stringWithFormat: @ % @ _ % @, milk, fruit, [arr componentsJoinedByString: @ _];}
Use Time:
Man * man = [[Man alloc] init]; [man makeMilk: @ Ma milk fruit: @ apple food: @ fish, @ meat, @ chicken, @ duck, @ goose child, nil];