蘋果最近更新了一份關於調試的文檔。現在把那些不熟悉的知識記錄一下。
通過速寫記法輸出numbers
double myNumber = 7.7;
NSLog( @"number: %@", @ (myNumber) );
輸出:
number: 7.7
輸出環境信息
宏 | 格式說明符 | 描述 |
---|---|---|
__func__ | %s | 當前函數簽名 |
__LINE__ | %d | 在源代碼文件的當前行號 |
__FILE__ | %s | 源代碼文件的完整路徑 |
__PRETTY_FUNCTION__ | %s | 類似於__func__,但包括在C + +代碼中的詳細類型信息。 |
表達 | 格式說明符 | 描述 |
---|---|---|
NSStringFromSelector(_cmd) | %@ | 當前選擇器的名稱。 |
NSStringFromClass([self class]) | %@ | 當前對象類的名稱。 |
[[NSString stringWithUTF8String:__FILE__] lastPathComponent] | %@ | 源代碼文件的名稱。 |
[NSThread callStackSymbols] | %@ | 程序員可讀字符串的當前的堆棧跟蹤的的NSArray。僅可用於調試,不要呈現給最終用戶或在你的程序中做任何邏輯。 |
例子1:
NSLog( @"calling: %s", __PRETTY_FUNCTION__ );
輸出:
calling : -[MyObjectClassName pressButton:]
例子2:
NSLog( @"%@", [NSThread callStackSymbols] );
輸出:
2014-04-30 18:44:30.075 AVCustomEdit[52779:60b] (
0 AVCustomEdit 0x0000efa6 -[APLSimpleEditor buildCompositionObjectsForPlayback:] + 278
1 AVCustomEdit 0x0000686e -[APLViewController viewDidAppear:] + 590
2 UIKit 0x007a4099 -[UIViewController _setViewAppearState:isAnimating:] + 526
3 UIKit 0x007a4617 -[UIViewController __viewDidAppear:] + 146
4 UIKit 0x007a49aa -[UIViewController _executeAfterAppearanceBlock] + 63
5 UIKit 0x0069f0d0 ___afterCACommitHandler_block_invoke_2 + 33
6 UIKit 0x0069f055 _applyBlockToCFArrayCopiedToStack + 403
7 UIKit 0x0069ee9a _afterCACommitHandler + 568
8 CoreFoundation 0x029db2bf __CFRunLoopDoObservers + 399
9 CoreFoundation 0x029b9254 __CFRunLoopRun + 1076
10 CoreFoundation 0x029b89d3 CFRunLoopRunSpecific + 467
11 CoreFoundation 0x029b87eb CFRunLoopRunInMode + 123
12 GraphicsServices 0x0318b5ee GSEventRunModal + 192
13 GraphicsServices 0x0318b42b GSEventRun + 104
14 UIKit 0x00681f9b UIApplicationMain + 1225
15 AVCustomEdit 0x000026bd main + 141
16 libdyld.dylib 0x0269e701 start + 1
)
使用DEBUG
因爲NSLog會消耗資源,所以,我們需要在發佈程序後,把NSLog註釋掉。
初階技巧:
在項目的設置中,有一個被預定義的DEBUG。只有在調試時,它才被賦值爲1。所以,我們可以通過它來實現僅在 Debug 模式下編譯的 NSLog。
#if DEBUG
NSLog( @"preparing to press button!" );
#endif
輸出: preparing to press button!
高級技巧:
可以在pch文件中添加下面的代碼來實現只在調試時才進行輸出。
#ifdef DEBUG
#define NSLog(...) NSLog( __VA_ARGS__ )
#else
#define NSLog(...) {}
#endif