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]);

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

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

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]];