将任意数量的参数传递给方法?

时间:2012-04-02 00:47:06

标签: objective-c syntax methods arguments

  

可能重复:
  Define a method that has many (or infinite) arguments

我有以下方法,应该得到 n 参数。如何逐个访问这些参数?如何计算传递给此方法的参数数量?

Objective-C中的这个功能叫做什么?

- (void)containsPoints:(CGPoint)points, ...
{
   // Get number of points passed?
   // Access these points 1 by 1
}

1 个答案:

答案 0 :(得分:0)

来自here

#import <Cocoa/Cocoa.h>

@interface NSMutableArray (variadicMethodExample)

- (void) appendObjects:(id) firstObject, ...; // This method takes a nil-terminated list of objects.

@end

@implementation NSMutableArray (variadicMethodExample)

- (void) appendObjects:(id) firstObject, ...
{
  id eachObject;
  va_list argumentList;
  if (firstObject) // The first argument isn't part of the varargs list,
  {                                   // so we'll handle it separately.
    [self addObject: firstObject];
    va_start(argumentList, firstObject); // Start scanning for arguments after firstObject.
    while (eachObject = va_arg(argumentList, id)) // As many times as we can get an argument of type "id"
      [self addObject: eachObject]; // that isn't nil, add it to self's contents.
    va_end(argumentList);
  }
}

@end