Introduction to the
MLeaksFinder is the WeRead team’s open source iOS memory leak detection tool.
MLeaksFinder advantages:
No need to change the business code, just introduce the framework
2. It can accurately detect which object is not released
3. If this function is enabled in debug mode, online services are not affected
The principle of
MLeaksFinder adds a method to the base NSObject class, the -WillDealLoc method, which points to self with a weak pointer and, after a short period of time (3 seconds), calls -AssertNotDealloc through the weak pointer. -AssertNotDealloc is used to trigger assertions.
When we think that an object should be released, call this method before release. If it is released successfully after 2 seconds, weakSelf will point to nil and will not call -AsserTNotDealloc method, so it will not pop up and prompt leakage; If it is not released (leaked), -AssertNotDealloc is called.
- (BOOL)willDealloc {
__weak id weakSelf = self;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[weakSelf assertNotDealloc];
});
return YES;
}
- (void)assertNotDealloc {
NSAssert(NO, @“”);
}
Copy the code
MLeaksFinder will start with UIViewController and, using AOP, hook the POP and dismiss methods of UIViewController and UINavigationController. UIViewController’s viewDidDisappear method calls [self willDealloc] to iterate over related objects.In real projects, we find that sometimes a UIViewController gets freed, but its view doesn’t get freed, or a UIView gets freed, but one of its subviews doesn’t get freed. Such memory leaks are common, so it is necessary to traverse the entire ViewController tree based on UIViewController. We recursively traverse through the presentedViewController of UIViewController and the View property, the SUBviews property of UIView and so on. For some viewControllers, such as UINavigationController, UISplitViewController, etc., we also need to iterate over the viewControllers properties.