程序开发的时候,总会遇到这样那样的bug。有些情况下打印日志比较方便,更多的时候需要依靠Debug工具。
XCode为我们集成了图形化的调试工具,也提供了命令行接口,所以调试起来还是比较方便的。
如上图,左侧是图形化界面,右侧是命令行接口。
常用命令
p xxx :如果xxx是Object,打印地址,否则打印value
po xxx:xxx必须是Object,打印对象的description
expr xxx=???:将变量xxx的值修改成???
breakpoint set -n "-[UIView setFrame:]" :将断点设在某个方法上
breakpoint set --selector selectxxx:将断点设在某个selector上
watchpoint set variable xxx:设置变量断点,当变量被修改时会中断
watchpoint set expression -- xxx [-x byte_size]:设置内存区域断点,发生修改时会中断
异常断点:断点窗口左下角添加Add Exception Breakpoint,能在发生异常式断住
常见错误
EXC_BAD_ACCESS 内存访问错误
1、设置Enable Zombie Objects ,能够打印出一些有用信息
*** -[UIView superview]: message sent to deallocated instance 0xa081220
但有时候还不够,还想知道那个地址对应的对象是哪来的。需要再设置Malloc Stack。然后在命令行下执行malloc_history 线程号 内存地址
sudo malloc_history 1157 0x993baa0
就会打印出该地址对象的创建过程
malloc_history Report Version: 2.0
Process: DebugDemo [1157]
Path: /Users/minjieni/Library/Application Support/iPhone Simulator/7.0/Applications/0C40E6FA-9F86-462B-84E3-D480281EF48D/DebugDemo.app/DebugDemo
Load Address: 0x1000
Identifier: DebugDemo
Version: ??? (???)
Code Type: X86 (Native)
Parent Process: debugserver [1158]
Date/Time: 2013-10-11 22:53:17.117 +0800
OS Version: Mac OS X 10.8.4 (12E3200)
Report Version: 7
ALLOC 0x993baa0-0x993baff [size=96]: thread_1ea8a28 |start | main | UIApplicationMain | GSEventRun | GSEventRunModal | CFRunLoopRunInMode | CFRunLoopRunSpecific | __CFRunLoopRun | __CFRunLoopDoSources0 | __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ | _UIApplicationHandleEventQueue | -[UIApplication sendEvent:] | -[UIWindow sendEvent:] | -[UIWindow _sendTouchesForEvent:] | -[UIControl touchesEnded:withEvent:] | -[UIControl _sendActionsForEvents:withEvent:] | -[UIControl sendAction:to:forEvent:] | -[UIApplication sendAction:toTarget:fromSender:forEvent:] | -[UIApplication sendAction:to:from:forEvent:] | -[NSObject performSelector:withObject:withObject:] | -[ViewController gotoDetailViewController] | -[UIViewController presentViewController:animated:completion:] | -[UIViewController presentViewController:withTransition:completion:] | -[UIWindowController transition:fromViewController:toViewController:target:didEndSelector:animation:] | -[UIViewController _preferredInterfaceOrientationForPresentationInWindow:fromInterfaceOrientation:] | -[UIViewController shouldAutorotate] | -[UIViewController view] | -[UIViewController loadViewIfRequired] | -[DetailViewController viewDidLoad] | _objc_rootAlloc | class_createInstance | calloc | malloc_zone_calloc