how to pass variable arguments to another method?

佐手、 提交于 2020-01-09 02:14:47

问题


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
}

回答1:


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



回答2:


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



回答3:


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



回答4:


I think you could use macros to achieve same thing. Let's say you wanna pass aMethod's variable arguments to another

-(void) aMethod:(NSString *) a, ... {
}

You could define your another 'method' using macro though it is not a real method:

#define anotherMethod(_a_,...) [self aMethod:_a_,##__VA_ARGS__]

This is my solution.



来源:https://stackoverflow.com/questions/2391780/how-to-pass-variable-arguments-to-another-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!