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





5 comments:

(^oo^) bad girl (^oo^) said...

i like......

PostaL2600 said...

Isn't much easyer to use NSLog() ?

javacom said...

If you can printf to stdout, that means you can printf to other devices.

Anonymous said...

[str cStringUsingEncoding:NSUTF8StringEncoding]
should be written as
[str UTF8String]

Anonymous said...

PostaL2600 said...
Isn't much easyer to use NSLog() ?

No, 1) NSLog() prints to stderr. 2) NSLog() prepends the timestamp and other crap