开发者

Method with an array of inputs

开发者 https://www.devze.com 2023-02-08 05:46 出处:网络
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 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?


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


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


I haven't had experience with these variadic methods (as they're called), but there's some Cocoa functionality to deal with it.

From Apple's Technical Q&A QA1405 (code snippet):

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

Copied from http://developer.apple.com/library/mac/#qa/qa2005/qa1405.html


I would try this: http://www.numbergrinder.com/node/35

Apple provides access in their libraries for convenience. The way to know how many elements you have is by iterating over the list until you hit nil.

What I would recommend, however, if you want to pass a variable number of arguments into some method you're writing, just pass an NSArray and iterate over that array.

Hope this helps!

0

精彩评论

暂无评论...
验证码 换一张
取 消