iOS MLeaksFinder使用


一、MLeaksFinder - 简介

MLeaksFinder 是 WeRead 团队开源的iOS内存泄漏检测工具。

MLeaksFinder 提供了内存泄露检测更好的解决方案。引进 MLeaksFinder 后,就可以在日常的开发,调试业务逻辑的过程中自动地发现并警告内存泄漏。开发者无需打开 Instrument 等工具,也无需为了找内存泄漏而去跑额外的流程。并且,由于开发者是在修改代码之后一跑业务逻辑就能发现内存泄漏的,这使得开发者能很快地意识到是哪里的代码写得问题。这种及时的内存泄漏的发现在很大的程度上降低了修复内存泄漏的成本。

当发生内存泄漏时,MLeaksFinder会用弹窗alert的形式告诉开发者内存泄漏的对象,开发者可以把alert关掉,并继续调试业务逻辑。

二、安装

1
pod 'MLeaksFinder'

MLeaksFinder在Pod安装后生效,无需添加任何代码或导入任何头文件。

注意:由于Facebook的BSD-plus-Patents许可证,FBRetainCycleDetector已从podspec中删除。 如果要使用FBRetainCycleDetector查找保留周期,请将pod’FBRetainCycleDetector’添加到项目的Podfile中,然后在MLeaksFinder.h中打开宏MEMORY_LEAKS_FINDER_RETAIN_CYCLE_ENABLED。

安装之后遇到编译出错的问题:Cannot initialize a parameter of type 'id<NSCopying> _Nonnull' with an rvalue of type

解决方案:修改podfile文件内容(删除之前pod下来的库,修改完podfile重新pod一下即可)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
project 'iOS.xcodeproj'
platform :ios, '10.0'

target 'iOS' do
use_frameworks!

pod 'YYKit'
pod 'NullSafe'
pod 'MLeaksFinder'

target 'iOSTests' do
inherit! :search_paths
end

target 'iOSUITests' do
end

#新增部分
post_install do |installer|
## Fix for XCode 12.5
find_and_replace("Pods/FBRetainCycleDetector/FBRetainCycleDetector/Layout/Classes/FBClassStrongLayout.mm",
"layoutCache[currentClass] = ivars;", "layoutCache[(id<NSCopying>)currentClass] = ivars;")
end

end

#新增部分
def find_and_replace(dir, findstr, replacestr)
Dir[dir].each do |name|
text = File.read(name)
replace = text.gsub(findstr,replacestr)
if text != replace
puts "Fix: " + name
File.open(name, "w") { |file| file.puts replace }
STDOUT.flush
end
end
Dir[dir + '*/'].each(&method(:find_and_replace))
end

三、使用方式

把 MLeaksFinder 目录下的文件添加到你的项目中,就可以在运行时(debug 模式下)帮助你检测项目里的内存泄露了,无需修改任何业务逻辑代码,而且只在 debug 下开启,完全不影响你的 release 包。

把 MLeaksFinder 目录下的文件添加到你的项目中,就可以在运行时(debug 模式下)帮助你检测项目里的内存泄露了,无需修改任何业务逻辑代码,而且只在 debug 下开启,完全不影响你的 release 包。

亦可手动引入,直接把 MLeaksFinder 的代码放到项目里即生效。如果把 MLeaksFinder 做为子工程,需要在主工程的 Build Settings -> Other Linker Flags 加上 -ObjC。

引入后,先验证引入是否成功,在UIViewController+MemoryLeak.m的+ (void)load方法中添加断点,app启用时进入该方法便引入成功。

引进 MLeaksFinder 的代码后即可检测内存泄漏,但查找循环引用的功能还未生效。可以再手动加入 FBRetainCycleDetector 代码,然后把 MLeaksFinder.h 里的 //#define MEMORY_LEAKS_FINDER_RETAIN_CYCLE_ENABLED 1 打开。

MLeaksFinder 默认只在 debug 下生效,当然也可以通过 MLeaksFinder.h 里的 //#define MEMORY_LEAKS_FINDER_ENABLED 0 来手动控制开关。