【发布时间】: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