谁能解释一下 NSLog 和 NSLogv 的区别?我知道 NSLog
用于在控制台打印数据。但是什么是 NSLogv
?
最佳答案
假设您想编写一个类似于 NSLog 的函数,但它除了记录消息外还将消息保存到一个数组中。您将如何实现?
如果你写一个variadic function void MySpecialLog(NSString *format, ...)
,有人可以像 NSLog 一样调用你的函数 — MySpecialLog(@"Hello %@!", name);
— 但是访问 format
之外的额外参数的唯一方法是使用 a va_list
.没有 splat operator在 C 或 Obj-C 中允许您将它们直接传递给函数内的 NSLog。
NSLogv 通过 va_list
一次接受所有附加参数来解决这个问题。它的签名是 void NSLogv(NSString *format, va_list args)
。您可以使用它来构建您自己的 NSLog 包装器。
Objective-C
void MySpecialLog(NSString *format, ...)
NS_FORMAT_FUNCTION(1, 2)
// The NS_FORMAT_FUNCTION attribute tells the compiler to treat the 1st argument like
// a format string, with values starting from the 2nd argument. This way, you'll
// get the proper warnings if format specifiers and arguments don't match.
{
va_list args;
va_start(args, format);
// Do something slightly more interesting than just passing format & args through...
NSString *newFormat = [@"You've called MySpecialLog()! " stringByAppendingString:format];
NSLogv(newFormat, args);
va_end(args);
}
您甚至可以使用相同的技术通过 Obj-C 方法包装 NSLog。 (因为 -[NSString initWithFormat:]
有一个类似的变体,叫做 -initWithFormat:arguments:
,你也可以把它包装起来。)
- (void)log:(NSString *)format, ... NS_FORMAT_FUNCTION(1, 2)
{
// Similarly to the above, we can pass all the arguments to -initWithFormat:arguments:.
va_list args;
va_start(args, format);
NSString *message = [[NSString alloc] initWithFormat:format arguments:args];
va_end(args);
// Why not both?
va_start(args, format);
NSLogv(format, args);
va_end(args);
}
swift
在 Swift 中,您可以使用接受 CVarArg...
的可变参数函数来做到这一点:
func mySpecialLog(_ format: String, _ args: CVarArg...) {
withVaList(args) {
NSLogv("You've called mySpecialLog()! " + format, $0)
}
}
关于objective-c - NSLog 和 NSLogv 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40968210/