iOS 內(nèi)存泄漏三兩事

相信大家都有過重寫 dealloc 方法來檢查某個 view controller 在消失后是否被釋放的經(jīng)歷棍厌。這幾乎是 iOS 中尋找由于引用循環(huán)造成內(nèi)存泄漏最有效的方法了。基本上每次發(fā)布蒜危,都會做很多次這種事情。不得不說這件事情很無聊,并且很可能會出錯警没。如果我們在日常的開發(fā)中, 提前的學習相關(guān)的知識, 那該多好?

下面是兩個很少見的 UIViewController的屬性:

  • isBeingDismissed 當一個模態(tài)推送出來的 view controller 正在消失的時候, 為: true.
  • isMovingFromParentViewController ,當一個 view controller 正在從它的父 view contrlller 中移除的時候(包括從系統(tǒng)的容器試圖比如說 UINavigationController), 為true.

如果這兩個屬性有一個是 true 的話, 這個 view controller 就會自動的被釋放掉振湾。我們不知道一個 view contrller 完成內(nèi)部狀態(tài)的改變杀迹,并且被 ARC 釋放掉需要耗費多長的時間。為了簡單起見押搪,我們假設(shè)它不會超過兩秒树酪。

1.現(xiàn)在看看下面的代碼(文末會有OC版):

extension UIViewController {
    public func dch_checkDeallocation(afterDelay delay: TimeInterval = 2.0) {
        let rootParentViewController = dch_rootParentViewController

        // We don’t check `isBeingDismissed` simply on this view controller because it’s common
        // to wrap a view controller in another view controller (e.g. in UINavigationController)
        // and present the wrapping view controller instead.
        if isMovingFromParentViewController || rootParentViewController.isBeingDismissed {
            let type = type(of: self)
            let disappearanceSource: String = isMovingFromParentViewController ? "removed from its parent" : "dismissed"

            DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: { [weak self] in
                assert(self == nil, "\(type) not deallocated after being \(disappearanceSource)")
            })
        }
    }

    private var dch_rootParentViewController: UIViewController {
        var root = self

        while let parent = root.parent {
            root = parent
        }

        return root
    }
}

在延時操作這個閉包中,我們首先通過 [weak self] 來避免這個閉包強引用self大州。然后通過斷言讓程序在 self 不為空的時候拋出異常续语。只有存在循環(huán)引用的情況下這個 view controller 才不為空。

現(xiàn)在我們需要做的就是在 viewDidDisappear 中調(diào)用這個方法摧茴。只要是你需要檢查它在消失后是不是被釋放掉的 view controller 都需要添加這個方法绵载。

override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)

    dch_checkDeallocation()
}

如果發(fā)聲了內(nèi)存泄漏,我們就會得到下面的斷言:

這個時候苛白,我們只需要打開 Xcode 的 Memory Graph Debugger 找到并且解決這些循環(huán)引用娃豹。

  1. 另外在 twitter 上也看到了類似的解決方案。

3.使用國人寫的 MLeaksFinder 在每次發(fā)生內(nèi)存泄漏的時候都會彈窗购裙。并且沒有代碼侵入性懂版,只需要使用 CocosPod 導入就可以了。

4.在使用圖片資源的時候躏率,少使用 imageNamed: 方法去獲取使用頻次不高的圖片資源躯畴。因為使用 imageNamed:加載的圖片資源會一直存在內(nèi)存里面民鼓, 對內(nèi)存的浪費也是巨大的。

5.上面的方法寫了一個 OC 版本的:

.h:

#import <UIKit/UIKit.h>

@interface UIViewController (FindLeaks)


// 默認為 NO
@property (nonatomic) BOOL noCheckLeaks;

@end

.m:

//
//  UIViewController+FindLeaks.m
//  Leaks
//
//  Created by sunny on 2017/8/27.
//  Copyright ? 2017年 CepheusSun. All rights reserved.
//

#import "UIViewController+FindLeaks.h"
#import <objc/runtime.h>

static const char *noCheckLeaksKey = "noChechLeaksKey";

@interface NSObject (MethodSwizzling)

+ (void)sy_swizzleInstanceSelector:(SEL)origSelector
                   swizzleSelector:(SEL)swizzleSelector;

@end

@implementation UIViewController (FindLeaks)

#pragma mark - Binding Property
- (BOOL)noCheckLeaks {
    return [objc_getAssociatedObject(self, noCheckLeaksKey) boolValue];
}

- (void)setNoCheckLeaks:(BOOL)noCheckLeaks {
    objc_setAssociatedObject(self, noCheckLeaksKey, [NSNumber numberWithBool:noCheckLeaks], OBJC_ASSOCIATION_RETAIN_NONATOMIC);

}

#pragma mark - Check
+ (void)load {
    
#if DEBUG
    [self sy_swizzleInstanceSelector:@selector(viewDidDisappear:) swizzleSelector:@selector(fl_viewDidDisappear:)];
#endif
}

- (void)fl_viewDidDisappear:(BOOL)animated {
    [self fl_viewDidDisappear:animated];
    if (!self.noCheckLeaks) {
        [self fl_checkDeallocationAfterDelay:2];
    }
}

- (void)fl_checkDeallocationAfterDelay:(NSTimeInterval)delay {
    UIViewController *root = [self fl_rootParentViewController];
    if (self.isMovingFromParentViewController || root.isBeingDismissed) {
        NSString *type = NSStringFromClass([self class]);
        NSString *disappearanceSource = self.isMovingFromParentViewController ? @"removed from its parent" : @"dismissed";
        __weak typeof(self) weakSelf = self;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSString *assert = [NSString stringWithFormat:@"%@ not deallocated after being %@",
             type, disappearanceSource];
            NSAssert(weakSelf == nil,assert);
        });
    }
}

- (UIViewController *)fl_rootParentViewController {
    UIViewController *root = self;
    while (root.parentViewController) {
        root = root.parentViewController;
    }
    return root;
}

@end

@implementation NSObject (MethodSwizzling)

+ (void)sy_swizzleInstanceSelector:(SEL)origSelector
                   swizzleSelector:(SEL)swizzleSelector {
    
    Method origMethod = class_getInstanceMethod(self, origSelector);
    Method swizzleMethod = class_getInstanceMethod(self, swizzleSelector);
    
    BOOL isAdd = class_addMethod(self, origSelector, method_getImplementation(swizzleMethod), method_getTypeEncoding(swizzleMethod));
    
    if (!isAdd) {
        method_exchangeImplementations(origMethod, swizzleMethod);
    }else {
        class_replaceMethod(self, swizzleSelector, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
    }
}


@end

只需要在不需要檢查的方法中設(shè)置屬性為 YES 就好了蓬抄。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末丰嘉,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子嚷缭,更是在濱河造成了極大的恐慌饮亏,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,546評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件阅爽,死亡現(xiàn)場離奇詭異路幸,居然都是意外死亡,警方通過查閱死者的電腦和手機付翁,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,224評論 3 395
  • 文/潘曉璐 我一進店門简肴,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人百侧,你說我怎么就攤上這事砰识。” “怎么了移层?”我有些...
    開封第一講書人閱讀 164,911評論 0 354
  • 文/不壞的土叔 我叫張陵仍翰,是天一觀的道長。 經(jīng)常有香客問我观话,道長予借,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,737評論 1 294
  • 正文 為了忘掉前任频蛔,我火速辦了婚禮灵迫,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘晦溪。我一直安慰自己瀑粥,他們只是感情好,可當我...
    茶點故事閱讀 67,753評論 6 392
  • 文/花漫 我一把揭開白布三圆。 她就那樣靜靜地躺著狞换,像睡著了一般。 火紅的嫁衣襯著肌膚如雪舟肉。 梳的紋絲不亂的頭發(fā)上修噪,一...
    開封第一講書人閱讀 51,598評論 1 305
  • 那天,我揣著相機與錄音路媚,去河邊找鬼黄琼。 笑死,一個胖子當著我的面吹牛整慎,可吹牛的內(nèi)容都是我干的脏款。 我是一名探鬼主播围苫,決...
    沈念sama閱讀 40,338評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼撤师!你這毒婦竟也來了剂府?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,249評論 0 276
  • 序言:老撾萬榮一對情侶失蹤剃盾,失蹤者是張志新(化名)和其女友劉穎周循,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體万俗,經(jīng)...
    沈念sama閱讀 45,696評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,888評論 3 336
  • 正文 我和宋清朗相戀三年饮怯,在試婚紗的時候發(fā)現(xiàn)自己被綠了闰歪。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,013評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡蓖墅,死狀恐怖库倘,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情论矾,我是刑警寧澤教翩,帶...
    沈念sama閱讀 35,731評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站贪壳,受9級特大地震影響饱亿,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜闰靴,卻給世界環(huán)境...
    茶點故事閱讀 41,348評論 3 330
  • 文/蒙蒙 一彪笼、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧蚂且,春花似錦配猫、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,929評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至淑翼,卻和暖如春腐巢,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背窒舟。 一陣腳步聲響...
    開封第一講書人閱讀 33,048評論 1 270
  • 我被黑心中介騙來泰國打工系忙, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人惠豺。 一個月前我還...
    沈念sama閱讀 48,203評論 3 370
  • 正文 我出身青樓银还,卻偏偏與公主長得像风宁,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子蛹疯,可洞房花燭夜當晚...
    茶點故事閱讀 44,960評論 2 355

推薦閱讀更多精彩內(nèi)容