Tuesday, July 8, 2008

[How-to] print NSString to stdout

This is how to print the NSString to stdout so that it can display in debug console window of Xcode.


main.m : Select all

#import <Foundation/Foundation.h>

void NSPrint (NSString *str)
{
[str writeToFile:@"/dev/stdout" atomically:NO encoding:NSUTF8StringEncoding error:nil];
}

void NSPrintUTF8 (NSString *str)
{
printf("%s", [str cStringUsingEncoding:NSUTF8StringEncoding]);
}

void NSPrintMac (NSString *str)
{
printf("%s", [str cStringUsingEncoding:NSMacOSRomanStringEncoding]);
}

#if defined(TARGET_IPHONE_SIMULATOR)
#define LogMethod() printf("%s\n", [[NSString stringWithFormat:@"Simulator-[%@ %s]", self, _cmd] cStringUsingEncoding:NSUTF8StringEncoding]);
#else
#define LogMethod() NSLog(@"-[%@ %s]", self, _cmd])
#endif


int main(int argc, char *argv[]) {
NSPrint(@"Hello, World\n");
NSPrintMac(@"Hello, Mac Encoding World\n");
LogMethod();
}


This is how to print out the NSString and append to a text file.


appendtxt.m : Select all

NSFileHandle *aFileHandle = [NSFileHandle fileHandleForWritingAtPath:[@"/tmp/myapp.log" stringByExpandingTildeInPath]];
[aFileHandle truncateFileAtOffset:[aFileHandle seekToEndOfFile]];
[aFileHandle writeData:[[NSString stringWithFormat:@"Simulator-[%@ %s]", self, _cmd] dataUsingEncoding:NSUTF8StringEncoding]];
[aFileHandle writeData:[NSStringFromCGSize(contentSize) dataUsingEncoding:NSUTF8StringEncoding]];