3

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

Community
  • 1
  • 1
sagarkothari
  • 24,520
  • 50
  • 165
  • 235
  • Also, questions not related to the Xcode IDE itself **should not use the Xcode tag.** This question would stay the same if you used nano and make to build your iOS apps. –  Oct 09 '12 at 05:41
  • Also http://stackoverflow.com/questions/5260840/objective-c-implement-method-which-takes-array-of-arguments – rob mayoff Oct 09 '12 at 06:20
  • Also http://stackoverflow.com/questions/11067358/methods-and-optional-parameters – rob mayoff Oct 09 '12 at 06:21
  • Also http://stackoverflow.com/questions/2214652/how-do-i-pass-a-nil-terminted-list-of-strings-to-an-objective-c-function – rob mayoff Oct 09 '12 at 06:22

2 Answers2

6

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
Community
  • 1
  • 1
Neo
  • 2,807
  • 1
  • 16
  • 18
  • 2
    It should be noted that this method expects a `nil` as the final parameter otherwise it will cause a segmentation fault as it runs off the end of the parameters. – mttrb Oct 09 '12 at 06:02
  • it should be called as [object yourMethods:arg1,arg2,arg3,nil]; but since the questioner just asked how to access the methods, i had not mentioned how to call the method... but as u mentioned in your comment i have added it in my answer... cheers – Neo Oct 09 '12 at 06:04
3

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.