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

人走茶凉 提交于 2019-11-30 23:14:32

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

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.

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