objective-c - NSLog 和 NSLogv 的区别

标签 objective-c swift nslog

谁能解释一下 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/

相关文章:

iphone - NSLog 导致 iPhone 应用程序在 Apple 应用程序审核期间崩溃

ios - 将使用 NSLog 视为构建错误

ios - 如何在 Objective-C 、iOS 中缩放/调整 CVPixelBufferRef 的大小

objective-c - 自动释放并分配给 nil

swift - 如何将 SKSpriteNode 放在 CAShapeLayer 前面?

ios - Swift - 集成 GameCenter 以使用排行榜

ios - 旋转后 UIWebView 内容未调整到新框架

ios - 如何解决此Mach-O Linker问题?

swift - 通过 NSAppleScript 编写 iTunes 脚本的沙盒权限

ios - "autoresize = W+H;"在 UIView 对象的 NSLog 输出中意味着什么