Realization of variable length parameter in objective-c

Source: Internet
Author: User

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.


OBJC does not provide a direct variable-length parameter method, which requires the use of the Av_list method in the C standard library, and is simply used as follows:

  1. -(void) Somethingforyou: (NSString *) vstring,.... {
  2. Va_list varlist;
  3. ID arg;
  4. Nsmutablearray *Argsarray = [[Nsmutablearray alloc]inti];
  5. if (vstring) {
  6. Va_start (varlist,vstring);
  7. while (arg = va_arg (varlist,id)) {
  8. [Argsarray Addobject:arg];
  9. }
  10. Va_end (varlist);
  11. }
  12. }

C Language Library files

Va_list argList: Defines a pointer to a variable number of parameter lists;
Va_start (arglist,statement): Causes the argument list pointer arg_ptr to point to the first optional parameter in the function argument list, stating: Argn is a fixed parameter before the first optional parameter, (or, last fixed argument; ...). Previous parameter), the order of the parameters in the function argument list in memory is consistent with the order in which the function is declared. If there is a declaration of a VA function that is void va_test (char A, char B, char C, ...), then its fixed parameters are a,b,c, the last fixed argument argn C, and therefore Va_start (Arg_ptr, C).

Va_arg (Arglist,id): Returns the parameter in the argument list that is referred to by the pointer arg_ptr, returns the type to, and causes the pointer arg_ptr to point to the next parameter in the parameter list.
Va_end (ARG_PTR): Clears the argument list and invalidates the parameter pointer arg_ptr.

Typical applications:

Add nil at the end of the argument at the time of the call

SqlHelper *sqlcom = [[SqlHelper alloc] init];
[Sqlcom somethingforyou:@ "INSERT into Authorinfo (author,age) VALUES (?,?)" @ "cheungching" @ "+", nil];

Realization of variable length parameter in objective-c

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.