如何将可选参数发送到另一个函数/方法?

时间:2009-07-26 18:19:35

标签: c objective-c

我有一个带有可选参数的指定初始化程序(类似于下面的代码),我想通过调用它来创建一个autorelease方法。有没有办法做到这一点?

@interface MyObject : NSObject

- (id)initWithArgs:(id)firstArg, ...;
+ (id)objectWithArgs:(id)firstArg, ...;

@end

@implementation MyObject

- (id)initWithArgs:(id)firstArg, ...
{
    if (!firstArg || ![super init]) {
        return nil
    }

    va_list argList;
    va_start(argList, firstArg);

    id currentObject = firstArg;
    do {
        NSLog(@"%@", currentObject);
    } while ((currentObject = va_arg(argList, id)) != nil);

    va_end(argList);
    return self;
}

+ (id)objectWithArgs:(id)firstArg, ...
{
    // return [[[MyObject alloc] initWithArgs:firstArg, ...] autorelease];
}

@end

2 个答案:

答案 0 :(得分:6)

你不能这样做。请参阅comp.lang.c FAQ。您可以做的最接近的事情是创建函数的两个版本,一个采用varargs(...),另一个采用va_list。然后,varargs版本可以将工作传递给va_list版本以避免重复代码:

@interface MyObject : NSObject

- (id)initWithArgs:(id)firstArg, ...;
- (id)init:(id)firstArg withVaList:(va_list)args;
+ (id)objectWithArgs:(id)firstArg, ...;
+ (id)object:(id)firstArg withVaList:(va_list)args;

@end

@implementation MyObject

- (id)initWithArgs:(id)firstArg, ...
{
    va_list args;
    va_start(args, firstArg);
    id result = [self init:firstArg withVaList:args];
    va_end(args);
    return result;
}

- (id)init:(id)firstArg withVaList:(va_list)args
{
    // do actual init here:
    while((id arg = va_arg(args, id)))
    {
        // ...
    }
}

+ (id)objectWithArgs:(id)firstArg, ...
{
    va_list args;
    va_start(args, firstArg);
    id result = [MyObject object:firstArg withVaList:args];
    va_end(args);
    return result;
}

+ (id)object:(id)firstArg withVaList:(va_list)args
{
    return [[[MyObject alloc] init:firstArg withVaList:args] autorelease];
}

@end

答案 1 :(得分:3)

通过方法重载在语言中执行默认参数的常用方法是:


function foo(bar, baz) {
  ... actual function code here ...
}

function foo(bar) {
  foo(bar, 42)
}