[英]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.
但我想将变量参数传递给另一种方法。 im 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
}
AFAIK ObjectiveC (just like C and C++) do not provide you with a syntax that allows what you directly have in mind. AFAIK ObjectiveC(就像C和C ++一样)没有为您提供可以直接考虑的语法。
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.
一个可以直接使用...调用,另一个可以被其他函数调用的函数以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]); }
You cannot pass variadic arguments directly. 您不能直接传递可变参数。 But some of these methods provide an alternative that you can pass a
va_list
argument eg 但是其中一些方法提供了一种替代方法,您可以传递
va_list
参数,例如
#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]);
}
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];
}
}
}
I think you could use macros to achieve same thing. 我认为您可以使用宏来实现相同的目的。 Let's say you wanna pass aMethod's variable arguments to another
假设您想将aMethod的变量参数传递给另一个
-(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. 这是我的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.