带有输入数组的方法

Dav*_*ndz 9 objective-c ios4

我想有一个方法,我可以像NSArray那样放置尽可能多的参数:

- (id)initWithObjects:(id)firstObj, ... NS_REQUIRES_NIL_TERMINATION;
Run Code Online (Sandbox Code Playgroud)

然后我可以使用:

NSArray *array = [[NSArray alloc] initWithObjects:obj1, obj2, ob3, nil];
Run Code Online (Sandbox Code Playgroud)

我可以添加尽可能多的对象,只要我在末尾添加'nil'告诉它我已经完成了.

我的问题是我怎么知道给出了多少论点,我将如何一次一个地通过它们?

Mar*_*pic 22

- (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);
  }
}
Run Code Online (Sandbox Code Playgroud)