kar*_*rim 2 iphone objective-c nslog variadic-functions ios
我对目标c变量参数函数一无所知.我想编写一个将采用nlsog类型参数的函数,但有时我会在该函数中使用NSLog.我怎样才能做到这一点?
-(void) printStatus:(NSString*)status, ...
{
// I want use use NSLog with all these parameter here.
// some gui logging also happens here
}
Run Code Online (Sandbox Code Playgroud)
电话会是这样的,
[self printStatus:@"status"];
Run Code Online (Sandbox Code Playgroud)
要么
[self printStatus:@"Staus: %@", someObject];
Run Code Online (Sandbox Code Playgroud)
而不是使用NSLog,我想使用printStatus.当我需要将控制台日志切换到GUI日志记录时,我只能更改为printStatus函数,而不是更改代码中的所有位置.
或者在我这里使用DLog,
#ifdef DEBUG
# define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)
#else
# define DLog(...) /* */
#endif
Run Code Online (Sandbox Code Playgroud)
你需要使用C的varargs类型和NSLogv宏:
-(void)printStatus:(NSString*)status, ...
{
va_list args;
va_start(args, status);
NSLogv(status, args);
va_end(args);
}
Run Code Online (Sandbox Code Playgroud)
这假设status参数是一个格式字符串,后跟参数.
如果要创建NSString格式字符串和参数(用于更新GUI),除此之外还可以执行以下操作NSLogv:
NSLogv(status, args);
NSString *message = [[NSString alloc] initWithFormat:status arguments:args];
// ... log to GUI
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1718 次 |
| 最近记录: |