Variable number of method parameters in Objective C - Need an example

后端 未结 2 1279
被撕碎了的回忆
被撕碎了的回忆 2021-01-06 05:58

From Objective C Programming Guide (Under the "Object Messaging" section),

Methods that take a variable number of parameters are also possible,

相关标签:
2条回答
  • 2021-01-06 06:35

    You can see this link.

    In your header file define the methods with three dots at the end

    -(void)yourMethods:(id)string1,...;
    

    And in you implementation file write the methods body

    -(void)yourMethods:(id)string1, ...{
    
        NSMutableArray *arguments=[[NSMutableArray alloc]initWithArray:nil];
        id eachObject;
        va_list argumentList;
        if (string1) 
        {
            [arguments addObject: string1];
            va_start(argumentList, string1); 
            while ((eachObject = va_arg(argumentList, id)))    
            {
                 [arguments addObject: eachObject];
            }
            va_end(argumentList);        
         }
        NSLog(@"%@",arguments);
    }
    

    Now call your method

    [self yourMethods:@"ab",@"cd",@"ef",@"gf",nil];
    

    NOTE: remember to put nil at the end

    0 讨论(0)
  • 2021-01-06 06:43

    The syntax for declaring a method with a variable number of arguments is like this:

    - (void) printMyClass: (int) x, ...;
    

    One argument is always the required minimum, the others can be accessed via the va_arg function group. For the exact details, see this tutorial.

    0 讨论(0)
提交回复
热议问题