Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

iphone - how to pass variable arguments to another method?

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
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...