MLeaksFinder源碼分析

基本原理:

MLeaksFinder是app運(yùn)行的過程中,檢測內(nèi)存泄漏的第三方庫,可以幫助在代碼調(diào)試階段發(fā)現(xiàn)問題。通過method swizzled hook 對象生命周期的方法,在對象結(jié)束生命周期的時(shí)候,在指定時(shí)間之后給對象發(fā)送某個(gè)消息。如果這個(gè)時(shí)候?qū)ο笠呀?jīng)被釋放,消息不會(huì)被執(zhí)行,如果沒有釋放說明發(fā)生了內(nèi)存泄漏,消息就會(huì)被執(zhí)行,從而提醒開發(fā)人員。通過遞歸的方式,會(huì)記錄下某個(gè)視圖或者controller的樹形節(jié)點(diǎn)的位置,能更好的幫助定位到具體哪個(gè)對象沒有被釋放。MLeaksFinder引入了FBRetainCycleDetector,可以檢查循環(huán)引用。

內(nèi)存泄漏分為2種,第1種是對象沒有被任何引用,在內(nèi)存中沒有被釋放。第2種是對象發(fā)生循環(huán)引用,無法被釋放。在RAC的場景下,通過是2引起的內(nèi)存泄漏。

源碼分析:

MLeaksFinder.h定義了MLeaksFinder中使用的宏

MLeaksFinder.h

#ifdef MEMORY_LEAKS_FINDER_ENABLED
 
 
//_INTERNAL_MLF_ENABLED 宏用來控制 MLLeaksFinder庫 
//什么時(shí)候開啟檢測,可以自定義這個(gè)時(shí)機(jī),默認(rèn)則是在DEBUG模式下會(huì)啟動(dòng),RELEASE模式下不啟動(dòng)
//它是通過預(yù)編譯來實(shí)現(xiàn)的
#define _INTERNAL_MLF_ENABLED MEMORY_LEAKS_FINDER_ENABLED
 
#else
 
#define _INTERNAL_MLF_ENABLED DEBUG
 
#endif
 
//_INTERNAL_MLF_RC_ENABLED 宏用來控制 是否開啟循環(huán)引用的檢測
#ifdef MEMORY_LEAKS_FINDER_RETAIN_CYCLE_ENABLED
 
#define _INTERNAL_MLF_RC_ENABLED MEMORY_LEAKS_FINDER_RETAIN_CYCLE_ENABLED
 
 
//COCOAPODS 因?yàn)镸LLeaksFinder引用了第三庫用來檢查循環(huán)引用,所以必須是當(dāng)前項(xiàng)目中使用了COCOAP
//ODS,才能使用這個(gè)功能。
#elif COCOAPODS
 
#define _INTERNAL_MLF_RC_ENABLED COCOAPODS
 
#endif

MLLeakeObjectProxy用來對泄漏對象檢查循環(huán)引用

MLeakedObjectProxy

//用來檢查當(dāng)前泄漏對象是否已經(jīng)添加到泄漏對象集合中,如果是,就不再添加也不再提示開發(fā)者
+ (BOOL)isAnyObjectLeakedAtPtrs:(NSSet *)ptrs
{
    NSAssert([NSThread isMainThread], @"Must be in main thread.");
  
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
//全局用于保存泄漏對象的集合
        leakedObjectPtrs = [[NSMutableSet alloc] init];
    });
 
    if (!ptrs.count) {
        return NO;
    }
//NSSet求交集
    if ([leakedObjectPtrs intersectsSet:ptrs]) {
        return YES;
    } else {
        return NO;
    }
}
+ (void)addLeakedObject:(id)object {
 
    NSAssert([NSThread isMainThread], @"Must be in main thread.");
 
     
//創(chuàng)建用于檢查循環(huán)引用的objectProxy對象
    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
//帶有循環(huán)引用檢查功能的提示框
    [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
 
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)
buttonIndex {
 
#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;
 
//retainCycles中是找到的所有循環(huán)引用的鏈
        for (NSArray *retainCycle in retainCycles) {
 
            NSInteger index = 0;
 
            for (FBObjectiveCGraphElement *element in retainCycle) {
//找到當(dāng)前內(nèi)存泄漏對象所在的循環(huán)引用的鏈
                if (element.object == object) {
//把當(dāng)前對象調(diào)整到第一個(gè)的位置,方便查看
                    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
 
}

NSObject+MemoryLeak主要功能存儲(chǔ)對象的父子節(jié)點(diǎn)的樹形結(jié)構(gòu),method swizzle邏輯 ,白名單以及判斷對象是否發(fā)生內(nèi)存泄漏

NSObject+MemoryLeak

- (BOOL)willDealloc {
 
    NSString *className = NSStringFromClass([self class]);
//通過白名單可以配置哪些對象不納入檢查,例如一些單例
    if ([[NSObject classNamesInWhiteList] containsObject:className])
 
        return NO;
 
    NSNumber *senderPtr = objc_getAssociatedObject([UIApplication sharedApplication], kLatestSenderKey);
 
    if ([senderPtr isEqualToNumber:@((uintptr_t)self)])
 
        return NO;
 
    __weak id weakSelf = self;
//在特定時(shí)間檢查對象是否已經(jīng)發(fā)生內(nèi)存泄漏
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)
    ), dispatch_get_main_queue(), ^{
 
        __strong id strongSelf = weakSelf;
//如果對象已經(jīng)被釋放,strongSelf為nil 調(diào)用該方法什么也不發(fā)生
        [strongSelf assertNotDealloc];
 
    });
 
    return YES;
} 
  
//改方法被調(diào)用說明改對象已經(jīng)發(fā)生內(nèi)存泄漏
- (void)assertNotDealloc {
//檢查是否已經(jīng)記錄,如果是,不再提示用戶
    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]);
 
}
  
//主要通過遞歸來記錄每個(gè)節(jié)點(diǎn)在樹形結(jié)構(gòu)中的位置,以及父子節(jié)點(diǎn)的指針
- (void)willReleaseChildren:(NSArray *)children {
 
    NSArray *viewStack = [self viewStack];
 
    NSSet *parentPtrs = [self parentPtrs];
 
    for (id child in children) {
 
        NSString *className = NSStringFromClass([child class]);
 
        [child setViewStack:[viewStack arrayByAddingObject:className]];
 
        [child setParentPtrs:[parentPtrs setByAddingObject:@((uintptr_t)child)]];
 
        [child willDealloc];
    }
}
+ (void)swizzleSEL:(SEL)originalSEL withSEL:(SEL)swizzledSEL {
 
 
//通過預(yù)編譯控制是否hook方法
#if _INTERNAL_MLF_ENABLED
 
     
//通過預(yù)編譯控制是否檢查循環(huán)引用
#if _INTERNAL_MLF_RC_ENABLED
 
    // Just find a place to set up FBRetainCycleDetector.
 
    static dispatch_once_t onceToken;
 
    dispatch_once(&onceToken, ^{
 
        dispatch_async(dispatch_get_main_queue(), ^{
 
            [FBAssociationManager hook];
 
        });
 
    });
 
#endif
 
     
 
    Class class = [self class];
 
     
 
    Method originalMethod = class_getInstanceMethod(class, originalSEL);
 
    Method swizzledMethod = class_getInstanceMethod(class, swizzledSEL);
 
     
 
    BOOL didAddMethod =
//class_addMethod主要是用來給某個(gè)類添加一個(gè)方法,originalSEL相當(dāng)于是方法名稱,method_getIm
//plementtation是方法實(shí)現(xiàn), 它返回一個(gè)BOOL類型的值
//在當(dāng)前class中沒有叫originalSEL的方法(
//具體不是看interface里沒有沒有聲明,而是看implementaion文件里有沒有方法實(shí)現(xiàn)),
// 并且有swizzledMethod方法的實(shí)現(xiàn)
//這個(gè)時(shí)候該函數(shù)會(huì)返回true,其他情況均返回false
    class_addMethod(class,
 
                    originalSEL,
 
                    method_getImplementation(swizzledMethod),
 
                    method_getTypeEncoding(swizzledMethod));
 
     
 
    if (didAddMethod) {
//didAddMethod為true 說明swizzledMethod之前不存在,通過class_addMethod函數(shù)添加了一個(gè)名字叫origninalSEL,實(shí)現(xiàn)是swizzledMoethod函數(shù)。
        class_replaceMethod(class,
 
                            swizzledSEL,
 
                            method_getImplementation(originalMethod),
 
                            method_getTypeEncoding(originalMethod));
 
    } else {
//didAddMethod為false 說明swizzledMethod方法已經(jīng)存在,直接交換二者實(shí)現(xiàn)
        method_exchangeImplementations(originalMethod, swizzledMethod);
 
    }
 
#endif
 
}

UINavigationController + MemoryLeak 主要是通過UINavigationController的方法去檢測子UIViewController頁面的生命周期,UIViewController的生命周期由UINavigationController的方法和UIViewController自身的一些方法共同決定的。

UINavigationController + MemoryLeak

//現(xiàn)在在具體的類型中添加方法hook,加載load中并且調(diào)用dspatch_once來保證只初始化一次,load是必然會(huì)調(diào)用的,并且category的load方法調(diào)用和類自身的load方法調(diào)用是分開的,互不干擾。
+ (void)load {
 
    static dispatch_once_t onceToken;
 
    dispatch_once(&onceToken, ^{
 
        [self swizzleSEL:@selector(pushViewController:animated:) withSEL:@
        selector(swizzled_pushViewController:animated:)];
 
        [self swizzleSEL:@selector(popViewControllerAnimated:) withSEL:@
        selector(swizzled_popViewControllerAnimated:)];
 
        [self swizzleSEL:@selector(popToViewController:animated:) withSEL:@
        selector(swizzled_popToViewController:animated:)];
 
        [self swizzleSEL:@selector(popToRootViewControllerAnimated:) withSEL:@
        selector(swizzled_popToRootViewControllerAnimated:)];
 
    });
}
  
- (void)swizzled_pushViewController:(UIViewController *)viewController
 animated:(BOOL)animated {
 
    if (self.splitViewController) {
//這里主要是考慮到app中有使用splitViewController的情況的時(shí)候,下一個(gè)根頁面push之后,
//之前被pop的根頁面才會(huì)回收
        id detailViewController = objc_getAssociatedObject(self, 
            kPoppedDetailVCKey);
 
        if ([detailViewController isKindOfClass:[UIViewController class]]) {
//回收之前被pop的根頁面
            [detailViewController willDealloc];
 
            objc_setAssociatedObject(self, kPoppedDetailVCKey, nil, 
                OBJC_ASSOCIATION_RETAIN);
 
        }
 
    }
    [self swizzled_pushViewController:viewController animated:animated];
 
}
- (UIViewController *)swizzled_popViewControllerAnimated:(BOOL)animated {
 
    UIViewController *poppedViewController = [self swizzled_popViewControllerAnimated:animated];
 
    if (!poppedViewController) {
        return nil;
    }
     
    //當(dāng)前頁面是spliteViewController根頁面
    if (self.splitViewController &&
 
        self.splitViewController.viewControllers.firstObject == self &&
 
        self.splitViewController == poppedViewController.splitViewController) {
 
        objc_setAssociatedObject(self, kPoppedDetailVCKey, poppedViewController
            , OBJC_ASSOCIATION_RETAIN);
 
        return poppedViewController;
    }
     
 
    // 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;
 
}
  
- (NSArray<UIViewController *> *)swizzled_popToViewController:(
    UIViewController *)viewController animated:(BOOL)animated {
 
    NSArray<UIViewController *> *poppedViewControllers = [self 
    swizzled_popToViewController:viewController animated:animated];
     
//一次性pop多個(gè)頁面的時(shí)候,這些頁面的viewDidDisappear估計(jì)都沒有被調(diào)用,直接回收了
    for (UIViewController *viewController in poppedViewControllers) {
 
        [viewController willDealloc];
 
    }
 
    return poppedViewControllers;
 
}

UIViewController + MemoryLeak

- (void)swizzled_viewDidDisappear:(BOOL)animated {
    [self swizzled_viewDidDisappear:animated];
//僅僅當(dāng)是pop引起viewDidDisappear的時(shí)候才釋放(當(dāng)被擋住之后也會(huì)調(diào)用ViewDidDisappear)
    if ([objc_getAssociatedObject(self, kHasBeenPoppedKey) boolValue]) {
 
        [self willDealloc];
 
    }
 
}
  
- (void)swizzled_dismissViewControllerAnimated:(BOOL)flag 
completion:(void (^)(void))completion {
 
    [self swizzled_dismissViewControllerAnimated:flag completion:completion];
 
 //dismiss掉presentedViewController,釋放它 (但是什么時(shí)候當(dāng)前viewController被釋放呢)
    UIViewController *dismissedViewController = self.presentedViewController;
 
    if (!dismissedViewController && self.presentingViewController) {
//釋放自己
        dismissedViewController = self;
    }
 
    if (!dismissedViewController) return;
//以present出來的viewcontroller,不通過DidDisappear去判斷是否釋放了
    [dismissedViewController willDealloc];
 
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
禁止轉(zhuǎn)載,如需轉(zhuǎn)載請通過簡信或評論聯(lián)系作者。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容