1: 為工程運(yùn)行時(shí)加入 NSZombieEnabled 環(huán)境變量,并設(shè)為啟用,則在 EXC_BAD_ACCESS 發(fā)生時(shí),XCode 的 Console 會(huì)打印出問題描述。
首先雙擊 XCode 工程中,Executables 下的 可執(zhí)行模組,
在彈出窗口中,Variables to be set in the environment,添加 NSZombieEnabled,并設(shè)定為 YES,點(diǎn)擊選中復(fù)選框啟用此變量。
這樣,運(yùn)行 Objective-C 時(shí)會(huì)看到控制臺(tái)輸出錯(cuò)誤信息
這條消息對(duì)于定位問題有很好的提示作用。但是很多時(shí)候,只有這條提示是不夠的,我們需要更多的提示來(lái)幫助定位問題,這時(shí)候再加入 MallocStackLogging 來(lái)啟用malloc記錄。
當(dāng)錯(cuò)誤發(fā)生后,在終端執(zhí)行:
malloc_history ${App_PID} ${Object_instance_addr}
則會(huì)獲得相應(yīng)的 malloc 歷史記錄,比如對(duì)于上一個(gè)控制臺(tái)輸出
Untitled[3646:a0f] *** -[CFString release]: message sent to deallocated instance 0x10010d340
則我們可以在終端執(zhí)行,結(jié)果如下:
Buick-Wongs-MacBook-Pro:Downloads buick$ malloc_history 3646 0x10010d340
malloc_history Report Version: 2.0
Process: Untitled [3646]
Path: /Users/buick/Desktop/Untitled/build/Debug/Untitled
Load Address: 0×100000000
Identifier: Untitled
Version: ??? (???)
Code Type: X86-64 (Native)
Parent Process: gdb-i386-apple-darwin [3638]
Date/Time: 2011-02-01 15:07:04.181 +0800
OS Version: Mac OS X 10.6.6 (10J567)
Report Version: 6
ALLOC 0x10010d340-0x10010d357 [size=24]: thread_7fff70118ca0 |start | main | objc_msgSend | lookUpMethod | prepareForMethodLookup | _class_initialize | +[NSString initialize] | objc_msgSend | lookUpMethod | prepareForMethodLookup | _class_initialize | NXCreateMapTableFromZone | malloc_zone_malloc
—-
FREE 0x10010d340-0x10010d357 [size=24]: thread_7fff70118ca0 |start | main | objc_msgSend | lookUpMethod | prepareForMethodLookup | _class_initialize | _finishInitializing | free
ALLOC 0x10010d340-0x10010d357 [size=24]: thread_7fff70118ca0 |start | main | -[NSPlaceholderString initWithString:] | objc_msgSend | lookUpMethod | prepareForMethodLookup | _class_initialize | _class_initialize | +[NSMutableString initialize] | objc_msgSend | lookUpMethod | prepareForMethodLookup | _class_initialize | NXCreateMapTableFromZone | malloc_zone_malloc
—-
FREE 0x10010d340-0x10010d357 [size=24]: thread_7fff70118ca0 |start | main | -[NSPlaceholderString initWithString:] | objc_msgSend | lookUpMethod | prepareForMethodLookup | _class_initialize | _class_initialize | _finishInitializing | free
ALLOC 0x10010d340-0x10010d35f [size=32]: thread_7fff70118ca0 |start | main | -[NSCFString substringWithRange:] | CFStringCreateWithSubstring | __CFStringCreateImmutableFunnel3 | _CFRuntimeCreateInstance | malloc_zone_malloc
這樣就可以很快的定位出問題的代碼片段了,注意輸出的最后一行,,,這行雖然不是問題的最終原因,但是離問題點(diǎn)已經(jīng)很近了,隨著它找下去,八成就會(huì)找到問題。