MemoryLeaks 之 MLeaksFinder 原理解析

1. Apple 提供的工具检测内存泄漏


1.1 静态分析(Analyze)

- 逻辑错误:访问空指针或未初始化的变量
- Localizability Issue
- 声明错误:声明但从未使用
- 内存错误:nil passed to a callee that requires a non-null 1st parameter
- ...

1.2 Instruments (Leaks / Allocations)

- Allocations: 纪录了内存分配,用来优化内存使用的
- Leaks: 用来分析内存泄漏。ARC中引起的内存泄漏原因就是引用环。
Image_20211026101330.png
IMG_0008.PNG

2. MLeaksFinder检测内存泄漏


Apple 提供的工具检测内存泄漏,比较考验电脑的性能,且需要一个个场景重复操作,然后根据堆栈信息去排查,比较费时费力。MLeaksFinder可以自动在 App 运行过程检测到内存泄露的对象并立即提醒,无需打开额外的工具,也无需为了检测内存泄露而一个个场景去重复地操作。MLeaksFinder 目前能自动检测 UIViewController 和 UIView 对象的内存泄露,而且也可以扩展以检测其它类型的对象。是结合FBRetainCycleDetector的一个库

MLeaksFinder特性如下:

  1. 追踪对象的生命周期
  2. 查找循环引用链
  3. alert 弹框提示

截图:

出现弹框的三种情况

  1. 单例或者被 cache 起来复用

    在第一次 pop 的时候报 Memory Leak,在之后的重复 push 并 pop 同一个 ViewController 过程中,不报 Object Deallocated,也不报 Memory Leak。这种情况下我们可以确定该对象被设计成单例或者 cache 起来了。

Image_20211207162927.png
  1. 释放不及时的 View 或 ViewController

    在第一次 pop 的时候报 Memory Leak,在之后的重复 push 并 pop 同一个 ViewController 过程中,不断地报 Object Deallocated 和 Memory Leak。这种情况属于释放不及时的情况。

Image_20211207163125.png
  1. 真正的内存泄漏

    在第一次 pop 的时候报 Memory Leak,在之后的重复 push 并 pop 同一个 ViewController 过程中,不报 Object Deallocated,但每次 pop 之后又报 Memory Leak。这种情况下每回进入并退出一个页面后,就报有新的内存泄漏,同时被报泄漏的对象又从来没有释放过,可以确定是真正的内存泄漏。

    Image_20211207163347.png

原理分析

当一个 UIViewController 被 pop 或 dismiss 后,该 UIViewController 包括它的 view,view 的 subviews 等等将很快被释放(除非你把它设计成单例,或者持有它的强引用)。于是,我们只需在一个 ViewController 被 pop 或 dismiss 一小段时间后,看看该 UIViewController,它的 view,view 的 subviews 等等是否还存在。

具体的方法是,为基类 NSObject 添加一个方法 -willDealloc 方法,该方法的作用是,先用一个弱指针指向 self,并在一小段时间(3秒)后,通过这个弱指针调用 -assertNotDealloc,而 -assertNotDealloc 主要作用是直接中断言。

Image_20211208150340.png

这样,当我们认为某个对象应该要被释放了,在释放前调用这个方法,如果3秒后它被释放成功,weakSelf 就指向 nil,不会调用到 -assertNotDealloc 方法,也就不会中断言,如果它没被释放(泄露了),-assertNotDealloc 就会被调用中断言。这样,当一个 UIViewController 被 pop 或 dismiss 时(我们认为它应该要被释放了),我们遍历该 UIViewController 上的所有 view,依次调 -willDealloc,若3秒后没被释放,就会中断言。

源码分析

我们先来看下整个源码的目录结构:

00001.png

Push -> Pop整个流程:

Push: (UINavigationController+MemoryLeak)

- (void)swizzled_pushViewController:(UIViewController *)viewController animated:(BOOL)animated {
    if (self.splitViewController) {
        id detailViewController = objc_getAssociatedObject(self, kPoppedDetailVCKey);
        if ([detailViewController isKindOfClass:[UIViewController class]]) {
            [detailViewController willDealloc];
            objc_setAssociatedObject(self, kPoppedDetailVCKey, nil, OBJC_ASSOCIATION_RETAIN);
        }
    }
    [self swizzled_pushViewController:viewController animated:animated];
}

viewWillAppear: (UIViewController+MemoryLeak)

- (void)swizzled_viewWillAppear:(BOOL)animated {
    [self swizzled_viewWillAppear:animated];
    objc_setAssociatedObject(self, kHasBeenPoppedKey, @(NO), OBJC_ASSOCIATION_RETAIN);
}

Pop: (UINavigationController+MemoryLeak)

- (UIViewController *)swizzled_popViewControllerAnimated:(BOOL)animated {
    UIViewController *poppedViewController = [self swizzled_popViewControllerAnimated:animated];
    
    //.....

    // VC is not dealloced until disappear when popped using a left-edge swipe gesture
    extern const void *const kHasBeenPoppedKey;
    objc_setAssociatedObject(poppedViewController, kHasBeenPoppedKey, @(YES), OBJC_ASSOCIATION_RETAIN);
    
    return poppedViewController;
}

在swizzled_popViewControllerAnimated方法中只是将kHasBeenPoppedKey设置为YES,但是并没调用willDealloc,这是因为在使用左边缘滑动关闭的时候,要等到UIViewController disappear的时候才开始销毁,所以这里只是设置一个标记延迟调用willDealloc。

viewDidDisappear: (UIViewController+MemoryLeak)

- (void)swizzled_viewDidDisappear:(BOOL)animated {
    [self swizzled_viewDidDisappear:animated];
    if ([objc_getAssociatedObject(self, kHasBeenPoppedKey) boolValue]) {
        [self willDealloc];
    }
}

- (BOOL)willDealloc {
    if (![super willDealloc]) {
        return NO;
    }
    [self willReleaseChildren:self.childViewControllers];
    [self willReleaseChild:self.presentedViewController];
    if (self.isViewLoaded) {
        [self willReleaseChild:self.view];
    }
    return YES;
}

willDealloc: (NSObject+MemoryLeaK)

- (BOOL)willDealloc {
    NSString *className = NSStringFromClass([self class]);
  // 白名单过滤
    if ([[NSObject classNamesWhitelist] containsObject:className])
        return NO;
    
  // UIApplication+MemoryLeak会将当前sender保存起来,当一个事件发生的时候,UIControl会调用sendAction:to:forEvent:将行为消息转发到UIApplication对象,再由UIApplication对象调用其sendAction:to:fromSender:forEvent:方法来将消息分发到指定的target上,而如果我们没有指定target,则会将事件分发到响应链上第一个想处理消息的对象上。而如果子类想监控或修改这种行为的话,则可以重写这个方法。在UIApplication+MemoryLeak将最近正在执行的sender存储起来就是为了在这个地方与self进行对比,也就是说如果当前对象正在执行action那么就不再对该对象进行内存检测。否则就会延迟两秒调用assertNotDealloc方法。
    NSNumber *senderPtr = objc_getAssociatedObject([UIApplication sharedApplication], kLatestSenderKey);
    if ([senderPtr isEqualToNumber:@((uintptr_t)self)])
        return NO;
    
    __weak id weakSelf = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        __strong id strongSelf = weakSelf;
        [strongSelf assertNotDealloc];
    });
    
    return YES;
}

assertNotDealloc: (NSObject+MemoryLeak)

- (void)assertNotDealloc {
    if ([MLeakedObjectProxy isAnyObjectLeakedAtPtrs:[self parentPtrs]]) {
        return;
    }
    [MLeakedObjectProxy addLeakedObject:self];
    NSString *className = NSStringFromClass([self class]);
    NSLog(@"Possibly Memory Leak.\nIn case that %@ should not be dealloced, override -willDealloc in %@ by returning NO.\nView-ViewController stack: %@", className, className, [self viewStack]);
}

addLeakedObject: (MLeakedObjectProxy)

+ (void)addLeakedObject:(id)object {
    NSAssert([NSThread isMainThread], @"Must be in main thread.");
    
    MLeakedObjectProxy *proxy = [[MLeakedObjectProxy alloc] init];
    proxy.object = object;
    proxy.objectPtr = @((uintptr_t)object);
    proxy.viewStack = [object viewStack];
    static const void *const kLeakedObjectProxyKey = &kLeakedObjectProxyKey;
    objc_setAssociatedObject(object, kLeakedObjectProxyKey, proxy, OBJC_ASSOCIATION_RETAIN);
    
    [leakedObjectPtrs addObject:proxy.objectPtr];
    
#if _INTERNAL_MLF_RC_ENABLED
    [MLeaksMessenger alertWithTitle:@"Memory Leak"
                            message:[NSString stringWithFormat:@"%@", proxy.viewStack]
                           delegate:proxy
              additionalButtonTitle:@"Retain Cycle"];
#else
    [MLeaksMessenger alertWithTitle:@"Memory Leak"
                            message:[NSString stringWithFormat:@"%@", proxy.viewStack]];
#endif
}

alertWithTitle: (MLeaksMessenger)

// 在alertView方法中对通过FBRetainCycleDetector来检测循环引用,然后通过弹窗进行展示
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (!buttonIndex) {
        return;
    }
    
    id object = self.object;
    if (!object) {
        return;
    }
    
#if _INTERNAL_MLF_RC_ENABLED
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        FBRetainCycleDetector *detector = [FBRetainCycleDetector new];
        [detector addCandidate:self.object];
        NSSet *retainCycles = [detector findRetainCyclesWithMaxCycleLength:20];
        
        BOOL hasFound = NO;
        for (NSArray *retainCycle in retainCycles) {
            NSInteger index = 0;
            for (FBObjectiveCGraphElement *element in retainCycle) {
                if (element.object == object) {
                    NSArray *shiftedRetainCycle = [self shiftArray:retainCycle toIndex:index];
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [MLeaksMessenger alertWithTitle:@"Retain Cycle"
                                                message:[NSString stringWithFormat:@"%@", shiftedRetainCycle]];
                    });
                    hasFound = YES;
                    break;
                }
                
                ++index;
            }
            if (hasFound) {
                break;
            }
        }
        if (!hasFound) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [MLeaksMessenger alertWithTitle:@"Retain Cycle"
                                        message:@"Fail to find a retain cycle"];
            });
        }
    });
#endif
}

如果某个对象被检测到2秒内还没被释放,但是在2秒之后还是调用了dealloc释放了,那么这种不算是内存泄漏,所以会弹出Object Deallocated提示该对象已经被释放了,不属于内存泄漏。

- (void)dealloc {
    NSNumber *objectPtr = _objectPtr;
    NSArray *viewStack = _viewStack;
    dispatch_async(dispatch_get_main_queue(), ^{
        [leakedObjectPtrs removeObject:objectPtr];
        [MLeaksMessenger alertWithTitle:@"Object Deallocated"
                                message:[NSString stringWithFormat:@"%@", viewStack]];
    });
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容