当需要将 C 字节数组(不是 ASCII)的内容打印到控制台时,'printf' 的优势在于,在单步执行数组时,它不会在每次使用后返回。因此,阵列被简洁地打印在屏幕上。但是,打印输出实际到达屏幕通常需要一段时间,并且在绝望中,我有时会打开或关闭“终端”,因为这似乎会清除打印输出(“fflush”不会)。
另一方面,“NSLog”打印速度很快,但人们经常在这里和其他地方看到它必须在数组的每一步中应用。不幸的是,这会在每次使用后插入一个返回,甚至导致一个短数组覆盖页面并使其难以阅读或复制。
作为记录,我认为值得指出的是,有一个简单的解决方案,使用“NSMutableString”和“appendFormat”,可以在页面上打印。这是带有逗号、空格和括号的“花里胡哨”版本,我可以方便地进行测试。它构造为 C 函数并以十进制 (%d) 打印;对于其他格式,请参阅https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Strings/introStrings.html上的 Apple 的“字符串编程指南” 。
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.
}