我参考了这个 SO Answer在目标 C 中创建可变参数函数。我通过传递如下参数来测试您的代码:
[self logMessage:@"string: %@\n number: %@\n image: %@",
@"asdf",
[NSNumber numberWithInt:23],
[UIImage imageNamed:@"local.png"]];
并使用 NSLog() 编辑代码;
- (void)logMessage:(NSString *)format, ... {
va_list args;
va_start(args, format);
id arg = nil;
int i = 1;
NSLogv(format, args);
while ((arg = va_arg(args,NSString *))) {
NSLog(@"val: %d", i++);
/// Do your thing with arg here
//NSString *name = NSStringFromClass([arg class]);
//NSLog(@"string: %@", name);
}
va_end(args);
}
但输出如下:
2012-09-28 19:34:45.271 SIMO[2384:c07] string: asdf
number: 23
image: <UIImage: 0x8151f80>
2012-09-28 19:34:45.273 SIMO[2384:c07] val: 1
2012-09-28 19:34:45.273 SIMO[2384:c07] val: 2
2012-09-28 19:34:45.274 SIMO[2384:c07] val: 3
2012-09-28 19:34:45.274 SIMO[2384:c07] val: 4
2012-09-28 19:34:45.274 SIMO[2384:c07] val: 5
2012-09-28 19:34:45.275 SIMO[2384:c07] val: 6
2012-09-28 19:34:45.275 SIMO[2384:c07] val: 7
2012-09-28 19:34:45.276 SIMO[2384:c07] val: 8
这说明参数是 8,但我只通过了 3 (NSString, NSNumber, UIImage) 我无法理解这个概念.. 你能澄清一下吗 有人能澄清一下吗