打印一个NSString [英] Printing an NSString

查看:154
本文介绍了打印一个NSString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Objective-C中打印NSString的正确方法是什么?许多示例使用NSLog(),但根据文档:

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

NSLog是FoundationKit函数,用于将调试语句打印到控制台. ... NSLog的工作原理基本上类似于: fprintf(stderr,format_string,args ...);

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

对我来说有点像Win32/C ++中的_TRACE宏.我不想打印到stderr,我想打印到stdout.有人建议如下使用printf():

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

但是,这似乎在间接性上有一个额外的层次,可以打印NSString,而且它不像解决方案那样感觉".

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

推荐答案

这是 解决方案.

由于printf是纯C函数,因此无法识别Objective-C对象. (NSLog的格式化程序不同于printf的格式化程序.)因此,在格式化之前必须将其转换为C字符串.

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.

顺便说一句,您可以使用[str UTF8String]代替[str cStringUsingEncoding:NSUTF8StringEncoding].

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

这篇关于打印一个NSString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆