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

家住魔仙堡 提交于 2019-12-09 01:30:21

问题


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

Methods that take a variable number of parameters are also possible, though they’re somewhat rare. Extra parameters are separated by commas after the end of the method name. (Unlike colons, the commas are not considered part of the name.) In the following example, the imaginary makeGroup: method is passed one required parameter (group) and three parameters that are optional:

[receiver makeGroup:group, memberOne, memberTwo, memberThree];

I tried to create such a method and it shows an error

"Expected ';' after method prototype"

when I try to declare the below function in my interface file(.h file).

- (void) printMyClass: (int) x, (int) y, (int) z;

Can anyone give sample example to create such a method like makeGroup

Thank you


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/12454408/variable-number-of-method-parameters-in-objective-c-need-an-example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!