views:

583

answers:

4

HI,

i have googled and came to know that how to use the variable arguments. but i want to pass my variable arguments to another method. i m getting errors. how to do that ?

-(void) aMethod:(NSString *) a, ... {
  [self anotherMethod:a]; 
  // i m doing this but getting error. how to pass complete vararg to anotherMethod
}
A: 

Like this?

- (void)methodOne:(NSString *)object {
    NSLog(@"calling method one");
    [self methodTwo:object];
}

- (void)methodTwo:(NSString *)object {
    NSLog(@"Calling set string from first method: %@", object);
}

edit: maybe this link will help?

Coca with Love: Variable argument lists in cocoa

Convolution
You are getting the question wrong. He is asking about a variable count of attributes and hence the parameters are indeed separated by commas.
Till
yes, i m not talking about simple parameters. i m talking about varargs, variable arguments.
g.revolution
+3  A: 

AFAIK ObjectiveC (just like C and C++) do not provide you with a syntax that allows what you directly have in mind.

The usual workaround is to create two versions of a function. One that may be called directly using ... and another one called by others functions passing the parameters in form of a va_list.

..
[obj aMethod:@"test this %d parameter", 1337);
[obj anotherMethod:@"test that %d parameter", 666);
..

-(void) aMethod:(NSString *)a, ... 
{
    va_list ap;
    va_start(ap, a);

    [self anotherMethod:a withParameters:ap]; 

    va_end(ap);
}

-(void) anotherMethod:(NSString *)a, ...
{
    va_list ap;
    va_start(ap, a);

    [self anotherMethod:a withParameters:ap]; 

    va_end(ap);
}

-(void) anotherMethod:(NSString *)a withParameters:(va_list)valist 
{
    NSLog([[[NSString alloc] initWithFormat:a arguments:valist] autorelease]);
}
Till
There's a memory lean in -anotherMethod:withParameters: You need to add an autorelease to the [[NSString alloc] init]
Bill Garrison
true and corrected @Bill
Till
+2  A: 

You cannot pass variadic arguments directly. But some of these methods provide an alternative that you can pass a va_list argument e.g.

#include <stdarg.h>

-(void)printFormat:(NSString*)format, ... {
   // Won't work:
   //   NSString* str = [NSString stringWithFormat:format];

   va_list vl;
   va_start(vl, format);
   NSString* str = [[[NSString alloc] initWithFormat:format arguments:vl] autorelease];
   va_end(vl);

   printf("%s", [str UTF8String]);
}
KennyTM
A: 

Have you considered setting up your arguments in either an array or dictionary, and coding conditionally?

-(void) aMethodWithArguments:(NSArray *)arguments {
    for (id *object in arguments) {
        if ([object isKindOfClass:fooClass]) {
            //handler for objects that are foo
            [self anotherMethod:object];
        }
        if ([object isKindOfClass:barClass]) {
            //and so on...
            [self yetAnotherMethod:object];
        }
    }
}
JustinXXVII