利用Instrument Leak來發現App中的內存泄露

XCode提供了一組用於檢測內存,調試動畫,佈局等的工具。對於調試一些性能問題,內存問題很是方便。這裏咱們使用Leak來發現代碼中的內存泄露。app

在Leak中啓動咱們的應用開始監控:工具

注意,在監控的時候有兩種選擇:All Heap Allocation,All Heap Allocation & Anonymous VM.這裏咱們只須要關心All Heap Allocation。由於這纔是咱們App真實使用的內存。Anonymous VM是操做系統在咱們App啓動的時候爲進程預留的內存空間。它通常是大於App實際須要的內存大小的。而且這個大小咱們也控制不了,所以監控沒有意義。佈局

Focus on the heap allocations because your app has more control over heap allocations. Most of the memory allocations your app makes are heap allocations.性能

The VM in anonymous VM stands for virtual memory. When your app launches, the operating system reserves a block of virtual memory for your application. This block is usually much larger than the amount of memory your app needs. When your app allocates memory, the operating system allocates the memory from the block it reserved.動畫

Remember the second sentence in the previous paragraph. The operating system determines the size of the virtual memory block, not your app. That’s why you should focus on the heap allocations instead of anonymous VM. Your app has no control over the size of the anonymous VM.spa

Source: http://meandmark.com/blog/2014/01/instruments-heap-allocations-and-anonymous-vm/操作系統

上面圖中Instrument已經自動給咱們標識出了一些有泄露的地方Leak Check那一欄中打紅叉的位置。可是不少泄露仍是發現不了。這些泄露須要藉助下面所說的方法手工找出。調試

對當前分配內存作標記excel

咱們能夠經過Mark Generation來對當前內存作標記,每次標記Instrument會統計上次標記後新申請的內存,並會跟蹤這些內存的使用(是否釋放)。對象

 

經過這個功能,咱們就能夠檢測某些頁面中存在的內存泄露狀況。方法就是:

1. 在進入某頁面前,將內存作標記

2. 進入頁面,待內存穩定後,再次將內存作標記,這是標記列表中的對象都是當前頁面所建立的。Instrument固然也會跟蹤這些對象。

3. 在頁面中作些操做,而後退出頁面。這是上一步中標記下來的應該大部分都會釋放掉。剩下來的咱們須要檢查一下是否存在應該釋放可是沒有釋放的。像一些UI元素若是界面退出尚未釋放,說明存在內存泄露。下圖就是某個頁面退出後我對該頁面建立時的內存標記:

經過點擊上面列表的每個實例,咱們能夠看到每一個實例完整的引用計數修改記錄。若是是在咱們寫的代碼中發生修改的話,咱們還能看到代碼。這樣方便咱們找出致使泄露的根源。

 

上面的引用計數改變列表中,咱們須要找出那種+1以後沒有-1的記錄(通常都是咱們本身寫的代碼),而後找到對應的代碼。我這裏找的方法是:把這個列表拷貝到excel中,而後把全部非app代碼的記錄去掉,這樣找會容易找到一點。(不知道爲何這裏Instrument不提供篩選功能,否則會方便不少)

相關文章
相關標籤/搜索