Search code examples
objective-cvariablesparameterscocos2d-iphonevariadic

Variadic function in obj-C skips first argument


I'm having a problem passing a variable number of parameters to the function:

-(void)addCharacterToScene:(NSString *)name withFrames:(CCSpriteFrame*)frames,... {
    va_list args;
    va_start(args, frames);
    id arg = va_arg(args,CCSpriteFrame*);
    int i=1;
    while (arg) {
        NSString *frame_name = [NSString stringWithFormat:@"%@_%i",name,i];
        NSLog(@"%@ \n%@",frame_name, arg);
        [[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFrame:arg name:frame_name];
        arg = va_arg(args,CCSpriteFrame*);
        i++;
    }
    va_end(args);
}

The problem is that the function skips over the first argument. My call to the function looks like this:

[self addCharacterToScene:@"wiz" withFrames:wizardFrame1,wizardFrame2,wizardFrame3,nil];

I can pass a dummy object in the first position and that gives the desired result, but there must be a better solution. Thanks!


Solution

  • Instead of doing this the first time:

    id arg = va_arg(args,CCSpriteFrame*);
    

    Do:

    id arg = frames;
    

    A va_list starts after the argument you specify in the va_start function. So if you want to process that argument, you have to start with it yourself.