When the need arises to print to the console the contents of a C byte array (not ASCII), ‘printf’ has the advantage, when stepping through the array, that it does not put a return after each use. Thus the array is printed concisely across the screen. However, it often takes an age for the printout actually to reach the screen and in desperation, I sometimes open or close ‘Terminal’ as this seems to flush out the printout (‘fflush’ does not).
‘NSLog’, on the other hand, prints quickly but one often sees here and elsewhere that it must be applied with each step through the array. Unfortunately, this inserts a return after each use, causing even a short array to cover the page and making it difficult to read or copy.
For the record, I thought it worth pointing out that there is a simple solution, using ‘NSMutableString’ and ‘appendFormat’, that prints across the page. Here is the ‘bells and whistles’ version with commas, spaces and enclosing braces that I keep handy for testing purposes. It is constructed as a C function and prints in decimal (%d); for other formats see Apple’s ‘String Programming Guide’ at 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()prints tostderr, whereasprintf()prints tostdout. It seems that the standard output is not flushed but the standard error stream is - try usingfprintf(stderr, "format string: %d", array[index]);in order to print to stderr using aprintf()-style function.