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不提供筛选功能,否则会方便不少)