Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method with an array of inputs

I want to have a method where I can put as many arguments as I need like the NSArray:

- (id)initWithObjects:(id)firstObj, ... NS_REQUIRES_NIL_TERMINATION;

I can then use:

NSArray *array = [[NSArray alloc] initWithObjects:obj1, obj2, ob3, nil];

I can add as many objects as I want as long as I add 'nil' at the end to tell it I'm done.

My question is how would I know how many arguments were given, and how would I go through them one at a time?

like image 719
David Skrundz Avatar asked Feb 04 '11 02:02

David Skrundz


2 Answers

- (void)yourMethod:(id) firstObject, ...
{
  id eachObject;
  va_list argumentList;
  if (firstObject)
  {               
    // do something with firstObject. Remember, it is not part of the variable argument list
    [self addObject: firstObject];
    va_start(argumentList, firstObject);          // scan for arguments after firstObject.
    while (eachObject = va_arg(argumentList, id)) // get rest of the objects until nil is found
    {
      // do something with each object
    }
    va_end(argumentList);
  }
}
like image 160
Marco Mustapic Avatar answered Sep 27 '22 17:09

Marco Mustapic


I think what you're talking about is implementing a variadic method. This should help: Variable arguments in Objective-C methods

like image 43
Matt Avatar answered Sep 27 '22 16:09

Matt