Objective-c : Accessing variadic arguments in method [duplicate]

故事扮演 提交于 2020-01-01 17:00:17

问题


Possible Duplicate:
How to create variable argument methods in Objective-C
Variable number of method parameters in Objective C - Need an example

Following is an example of a method having variadic arguments.

- (void)numberOfParameters:group,... {
    NSLog(@"%@",group);
}

In above method, I know to access the first one of the variadic arguments. Would you please help me for accessing the others as well?

I am just going through ObjC.pdf & I am reading page number 35 & line number is 4


回答1:


See this almost same question

-(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);
}

Call it with nil parameter at the end as:

[object yourMethods:arg1,arg2,arg3,nil];// object can be self



回答2:


One: they're not called "group parameters" (as far as I know), but rather variadic arguments.

Two: the C standard library header stdarg.h provides data types and macros for this purpose (that's why I generally suggest to master plain ol' ANSI C first, before making The Best iPhone App Ever (TM)...)

#include <stdarg.h>

- (void)numberOfParameters:(int)num, ...
{
    int i;
    va_list args;
    va_start(args, num);

    for (i = 0; i < num; i++) {
        SomeType param = va_arg(args, SomeType);
        // do something with `param'
    }

    va_end(args);
}

Here's a rather good explanation on this topic.



来源:https://stackoverflow.com/questions/12793406/objective-c-accessing-variadic-arguments-in-method

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