Xcode 的除錯體驗和 Eclipse、Visual Studio 不太一樣,它不會自動把變數值攤在你眼前。但其實只要學會 lldb 的幾個指令,看變數比點滑鼠還快。
建立一個 Single View App,在 viewDidLoad 裡放幾行程式:
- (void)viewDidLoad {
[super viewDidLoad];
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"value1", @"key1",
@"28", @"age", @"rongfzh", @"name", nil];
UILabel *label = [[UILabel alloc] init];
label.frame = CGRectMake(20, 40, 250, 60);
label.text = [dic objectForKey:@"name"];
[self.view addSubview:label];
}
在最後一行打上中斷點,按 Command+R 啟動除錯。
在 Debug Console 的 lldb 提示符號後輸入:
(lldb) po dic
字典的內容就被完整印了出來。再試試 label:
(lldb) po label (UILabel *) $3 = 0x06a8bdd0 <UILabel: 0x6a8bdd0; frame = (20 40; 250 60); text = 'rongfzh'; clipsToBounds = YES; userInteractionEnabled = NO; layer = <CALayer: 0x6a8be90>>
除了物件本身,連 frame、文字、layer 位址都一併顯示,對排查版面問題特別有用。
(lldb) print (char*)[[dic description] cString]
(char *) $4 = 0x06d79760 "{\n age = 28;\n key1 = value1;\n name = rongfzh;\n}"
需要看整數、指標位址或計數時,用 print 搭配型別轉換最合適:
(lldb) print (int)[label retainCount] (int) $2 = 1
一個小結論:po 走的是物件的 description,適合看「這個東西是什麼」;print 表達的是「這個值的位元樣貌」,適合看純量與指標。兩者搭配,幾乎所有除錯現場的疑問都能就地解決。另外提醒,在現代不建議手動呼叫 retainCount 來判斷記憶體狀態,ARC 之下更應該用 Instruments 觀察實際的保留與釋放流程。