GDB 不是萬能的,可是沒有 GDB 卻是萬萬不能的。這裡簡單介紹 iOS 開發中最基本的幾個 GDB 命令。
po 是 print-object 的簡寫,可用來列印所有 NSObject 物件。
(gdb) po self <LauncherViewController: 0x552c570> (gdb) po [self view] <UIView: 0x544eb80; frame = (0 0; 320 411); autoresize = W+H; layer = <CALayer: 0x544ebb0>> (gdb) print-object [self view] <UIView: 0x544eb80; frame = (0 0; 320 411); autoresize = W+H; layer = <CALayer: 0x544ebb0>>
po 的本質是呼叫物件的 description 方法,因此你自訂類別時只要實作 description,就能讓 po 輸出好讀的內容,除錯效率會大幅提升。
p 是 print 的簡寫,用來列印所有簡單型別,如 int、float、結構體等。
(gdb) p self
$1 = (LauncherViewController *) 0x552c570
(gdb) p [[self view] size]
Unable to call function "objc_msgSend" at 0x1e7e08c: no return type information available.
To call this function anyway, you can cast the return type explicitly
(e.g. 'print (float) fabs (3.0)')
(gdb) p (CGSize)[[self view] size]
$1 = {
width = 320,
height = 411
}
(gdb) print (CGSize)[[self view] size]
$2 = {
width = 320,
height = 411
}
這個「no return type information available」的訊息幾乎每個人都遇過。原因很簡單:GDB 不知道 objc_msgSend 的傳回型別,也就無從得知該怎麼解讀結果。解法就是像範例那樣,明確地把傳回型別轉型出來。
call 就是「呼叫」的意思。其實上述的 po 和 p 也具備呼叫能力,因此一般只在不需要顯示輸出、或方法沒有傳回值時才用 call。
(gdb) call [[self view] sizeToFit] Unable to call function "objc_msgSend" at 0x1e7e08c: no return type information available. (gdb) call (void)[[self view] sizeToFit] (gdb) call [[self view] size] Unable to call function "objc_msgSend" at 0x1e7e08c: no return type information available. (gdb) call (void)[[self view] size]
同樣的道理:把傳回型別寫成 (void) 或明確的型別,GDB 就知道該怎麼處理了。call 的實用場景還包括「在程式中途臨時呼叫一個方法看結果」,例如 call (void)[self reloadData],不必重新編譯就能驗證假設。
Xcode 的除錯器為使用者提供了一個 GDB 的圖形界面。GDB 是 GNU 組織的開放原始碼除錯器。你可以在 Xcode 的圖形界面裡完成大部分事情;但如果你需要,也可以在命令列裡直接下 GDB 指令。
要在除錯的執行階段輸入 GDB 命令:
補充一點:在較新的 Xcode 中 GDB 已被 LLDB 取代,對應的指令分別是 po(列印物件)、p(列印運算式)與 expr(求值並可帶型別,如 expr -- (CGSize)[[self view] size])。概念完全相通,只是提示符號從 (gdb) 變成 (lldb)。