2011-08-11 61 views
20

一个非常基本的问题,我最近开始探索Objective C并试图混淆一个示例代码。然而,仅仅为了调试的目的,我想在控制台上输出NSString变量的值。我如何实现这一目标?如何通过NSLog打印变量的值?

基本上我是一个Java开发人员,所以我期待的类似的东西...

String hello = "world!"; 
System.out.println(hello); 

我在这个外语(的OBJ-C)是可变的...

NSString *hello = ...calling a method to return string... 

任何提示将不胜感激!

谢谢

回答

46

很简单:

NSLog(@"Value of hello = %@", hello); 
+0

我有一个代码完成快捷方式这一个:'的NSLog (@“[%@%@]”,NSStringFromClass([self class]),NSStringFromSelector(_cmd));'注意它给你类名,** NOT **你所在的文件。你有一个丰富的继承层次结构(大多数不),它可能在超类文件中,当它说“[subclass methodName]” – bshirley

+0

如果你发现[NSString类引用](http://developer.apple.com/ library/mac /#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html)并找到'stringWithFormat:',它提供了[Formatting String Objects(the basics)]的链接。 apple.com/library/mac/#documentation/Cocoa/Conceptual/Strings/Articles/FormatStrings.html#//apple_ref/doc/uid/20000943)和[字符串格式化说明符](http://developer.apple.com/ library/mac /#documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html#// apple_ref/doc/uid/TP40004265) - 仔细阅读它们! – bshirley

+0

也注意到,在上面的例子中(并且在调试器中使用'po'),将在该对象上调用' - (NSString *)描述'方法。您可以重写该方法以提供一些有趣的内容。 (简单的方法是将其转储到字典中,并调用字典中的“description”。 – bshirley

10
NSLog(@"%@",hello); 

基于数据类型%@变化如下

For Strings u use %@ 
For int u use %i 
For float u use %f 
For double u use %lf