2011-08-11 64 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