【问题标题】:ObjC: ‘NSLog’ versus ‘printf’ for printing C byte arraysObjC:用于打印 C 字节数组的“NSLog”与“printf”
【发布时间】:2012-11-16 17:41:23
【问题描述】:

当需要将 C 字节数组(不是 ASCII)的内容打印到控制台时,'printf' 的优势在于,在单步执行数组时,它不会在每次使用后返回。因此,阵列被简洁地打印在屏幕上。但是,打印输出实际到达屏幕通常需要一段时间,并且在绝望中,我有时会打开或关闭“终端”,因为这似乎会清除打印输出(“fflush”不会)。

另一方面,“NSLog”打印速度很快,但人们经常在这里和其他地方看到它必须在数组的每一步中应用。不幸的是,这会在每次使用后插入一个返回,甚至会导致一个短数组覆盖页面并使其难以阅读或复制。

作为记录,我认为值得指出的是,有一个简单的解决方案,使用“NSMutableString”和“appendFormat”,可以在页面上打印。这是带有逗号、空格和括号的“花里胡哨”版本,我可以方便地进行测试。它构造为 C 函数并以十进制 (%d) 打印;对于其他格式,请参阅 Apple 的“字符串编程指南”https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Strings/introStrings.html

void byteArrayLog(unsigned char *bArray, int numBytes)
{
    int i;  
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    NSMutableString* dString = [NSMutableString stringWithCapacity:5*numBytes];//Create a mutable string. Note the length.
    [dString appendString:@"{"];//Start with "{".
    for(i = 0; i < numBytes-1; i++)
        [dString appendFormat:@"%d, ", bArray[i]];//Format a byte, follow with a comma and a space.
    [dString appendFormat:@"%d}", bArray[i]];//Format the final byte, finish with a "}".

    NSLog(@"Array contents = %@", dString);//Print to the console.

    [pool drain];//Clean up.
}

【问题讨论】:

  • NSLog() 打印到 stderr,而 printf() 打印到 stdout。似乎标准输出没有刷新,但标准错误流是 - 尝试使用 fprintf(stderr, "format string: %d", array[index]); 以便使用 printf() 样式函数打印到 stderr。
  • asl 是苹果的系统日志,在 ios4/osx 10.6 中引入 :) man asl_search。它有一个很好的 api 用于查询旧日志
  • @Daij-Djan syslog 从标准错误中获取数据。
  • 好的 :) 不知道 :) 谢谢。 :) 只知道 printf 没有出现在 asl 中。我现在知道了 :D
  • 好建议@H2CO3。乍一看,它似乎工作。由于“fflush”不起作用,我无法探索那条路线。希望该帖子在其他情况下有用,因为这种困境似乎经常出现在帖子中。对于 NSBum,先发制人的问题有时也很有用:-)

标签: objective-c printf nslog


【解决方案1】:

NSLog() 打印到标准错误流 (stderr),而 printf() 打印到标准输出 (stdout)。似乎标准输出没有正确刷新,但标准错误流是 - 尝试使用

fprintf(stderr, "format string: %d", array[index]);

为了使用printf()-style 函数打印到stderr

【讨论】:

  • 这在短数组(约 10 字节)中很有效,但对于较长的数组(约 100 字节或更多),它会对数据进行分区;但是,远不及“NSLog”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-11
  • 1970-01-01
  • 2017-05-29
  • 1970-01-01
  • 2012-04-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多