how to pass variable arguments to another method?

前端 未结 4 1352
没有蜡笔的小新
没有蜡笔的小新 2020-11-30 05: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 ?

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-30 06:19

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

提交回复
热议问题