Alex Rivera | Logout

Printing an NSString

Asked 2010-02-07T07:20:17.530
32

What's the correct way to print an NSString in Objective-C? A lot of examples use NSLog(), but according to the documentation:

NSLog is a FoundationKit function for printing debug statements to the console. ... NSLog works basically like: fprintf(stderr, format_string, args ...);

Which to me is a bit like the _TRACE macro in Win32/C++. I don't want to print to stderr, I want to print to stdout. There are people who suggest using printf() as follows:

printf("%s", [str cStringUsingEncoding:NSUTF8StringEncoding]);

But this seems like an extra level on indirection to get the NSString printed, and it doesn't "feel" like the solution.

Edit
Report

1 Answer

26

Well this is the solution.

Since printf is a pure C function, it won't recognize the Objective-C objects. (NSLog's formatter is distinct from printf's one.) Therefore, you have to convert it into a C string before formatting.

BTW you can use [str UTF8String] instead of [str cStringUsingEncoding:NSUTF8StringEncoding].

answered 2010-02-07T07:31:44.063

Your Answer