Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
665 views
in Technique[技术] by (71.8m points)

objective c - Printing an NSString

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Spewing stuff to stdout is actually a pretty rare thing to do in Cocoa, given that almost all projects are GUI in nature. There are relatively few projects that are built as command line tools or otherwise need to deal with stdout.

However, the Foundation does provide the means to write to stdout. Specifically, NSFileHandle has fileHandleWithStandardOutput which gives you a file handle that can write to stdout.

From there, it is a matter of converting the NSString to an NSData and writing it.

Quite a few steps, but easily wrapped up in a reusable function:

void MyLog(NSString *format, ...) {
    va_list args;
    va_start(args, format);
    NSString *formattedString = [[NSString alloc] initWithFormat: format
                                                  arguments: args];
    va_end(args);
    [[NSFileHandle fileHandleWithStandardOutput]
        writeData: [formattedString dataUsingEncoding: NSNEXTSTEPStringEncoding]];
    [formattedString release];
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...