g.r*_*ion 40 iphone objective-c variadic-functions ios
我用Google搜索并了解了如何使用变量参数.但我想将我的变量参数传递给另一个方法.我得到错误.怎么做 ?
-(void) aMethod:(NSString *) a, ... {
[self anotherMethod:a];
// i m doing this but getting error. how to pass complete vararg to anotherMethod
}
Run Code Online (Sandbox Code Playgroud)
Til*_*ill 54
AFAIK ObjectiveC(就像C和C++一样)没有为您提供允许您直接考虑的语法.
通常的解决方法是创建一个函数的两个版本.一个可以直接使用...调用,另一个调用其他函数以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]); }
ken*_*ytm 20
您无法直接传递可变参数.但是这些方法中的一些提供了一种可以传递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]);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
18631 次 |
最近记录: |