Swift內(nèi)存泄漏詳解([weak self]使用場景)

// 這是一個非逃逸閉包(立即執(zhí)行),因此不需要弱引用
func uiViewAnimate() {
        UIView.animate(withDuration: 3.0) { self.view.backgroundColor = .red }
}
// 同樣對于高階函數(shù),也是非逃逸的,因此不需要弱引用[weak self]
    func higherOrderFunctions() {
        let numbers = [1,2,3,4,5,6,7,8,9,10]
        numbers.forEach { self.view.tag = $0 }
        numbers.forEach { num in
            DispatchQueue.global().async {
                print(num)
            }
        }
        _ = numbers.filter { $0 == self.view.tag }
    }
/*這會導(dǎo)致 Controller 內(nèi)存泄漏,因?yàn)槲覀儧]有立即執(zhí)行動畫。我們把它存儲為屬性
在閉包中使用了self,同時self也引用了閉包*/
func leakyViewPropertyAnimator() {
        // color won't actually change, because we aren't executing the animation
        let anim = UIViewPropertyAnimator(duration: 2.0, curve: .linear) { self.view.backgroundColor = .red }
        anim.addCompletion { _ in self.view.backgroundColor = .white }
        self.anim = anim
    }
/*如果我們將對要直接操作的屬性(view)的引用傳遞給閉包,而不是使用self,
*將不會導(dǎo)致內(nèi)存泄漏,即使不使用[weak self]*/
func nonLeakyViewPropertyAnimator1() {
        let view = self.view
        // color won't actually change, because we aren't executing the animation
        let anim = UIViewPropertyAnimator(duration: 2.0, curve: .linear) { view?.backgroundColor = .red }
        anim.addCompletion { _ in view?.backgroundColor = .white }
        self.anim = anim
    }
// 如果我們立即啟動動畫,沒有在其他地方進(jìn)行強(qiáng)引用,它不會泄漏控制器,即使沒有使用[weak self]
func nonLeakyViewPropertyAnimator2() {
        let anim = UIViewPropertyAnimator(duration: 2.0, curve: .linear) { self.view.backgroundColor = .red }
        anim.addCompletion { _ in self.view.backgroundColor = .white }
        anim.startAnimation()
    }
// 如果我們存儲一個閉包,它就會逃逸,如果我們不使用[weak self],它就會造成循環(huán)引用從而導(dǎo)致內(nèi)存泄漏
func leakyDispatchQueue() {
        let workItem = DispatchWorkItem { self.view.backgroundColor = .red }
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.0, execute: workItem)
        self. workItem = workItem
    }
// 如果我們立即執(zhí)行閉包而不存儲它,就不需要[weak self]
func nonLeakyDispatchQueue() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
            self.view.backgroundColor = .red
        }
        
        DispatchQueue.main.async {
            self.view.backgroundColor = .red
        }
        
        DispatchQueue.global(qos: .background).async {
            print(self.navigationItem.description)
        }
    }
/*此計(jì)時器將阻止控制器釋放,因?yàn)椋?*1、定時器重復(fù)執(zhí)行
*2、self在閉包中引用,而沒有使用[weak self]
*如果這兩個條件中的任何一個是錯誤的,它都不會引起問題*/
func leakyTimer() {
        let timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
            let currentColor = self.view.backgroundColor
            self.view.backgroundColor = currentColor == .red ? .blue : .red
        }
        timer.tolerance = 0.5
        RunLoop.current.add(timer, forMode: RunLoop.Mode.common)
    }
/*類似于UIViewPropertyAnimator,如果我們存儲一個URLSession任務(wù)而不立即執(zhí)行它,將導(dǎo)致內(nèi)存泄漏,除非我們使用[weak self]*/
func leakyAsyncCall() {
        let url = URL(string: "https://www.github.com")!
        let task = URLSession.shared.downloadTask(with: url) { localURL, _, _ in
            guard let localURL = localURL else { return }
            let contents = (try? String(contentsOf: localURL)) ?? "No contents"
            print(contents)
            print(self.view.description)
        }
        self.closureStorage = task
    }
/*如果立即執(zhí)行URLSession任務(wù),但設(shè)置了較長的超時間隔,則會延遲釋放
    *直到您取消任務(wù)、獲得響應(yīng)或超時。使用[weak self]可以防止延遲
    *注意:url使用端口81有助于模擬請求超時 */
func delayedAllocAsyncCall() {
        let url = URL(string: "https://www.google.com:81")!
        
        let sessionConfig = URLSessionConfiguration.default
        sessionConfig.timeoutIntervalForRequest = 999.0
        sessionConfig.timeoutIntervalForResource = 999.0
        let session = URLSession(configuration: sessionConfig)
        
        let task = session.downloadTask(with: url) { localURL, _, error in
            guard let localURL = localURL else { return }
            let contents = (try? String(contentsOf: localURL)) ?? "No contents"
            print(contents)
            print(self.view.description)
        }
        task.resume()
    }
/*這里導(dǎo)致了一個循環(huán)引用,因?yàn)殚]包和“self”相互引用而不是用[weak self],注意這里需要'@escaping',因?yàn)槲覀冋诒4骈]包(導(dǎo)致逃逸)以備以后使用。*/
func savedClosure() {
        
        func run(closure: @escaping () -> Void) {
            closure()
            self.closureStorage = closure // 'self' stores the closure
        }
        
        run {
            self.view.backgroundColor = .red // the closure references 'self'
        }
    }
/*這里不需要[weak self],因?yàn)殚]包沒有轉(zhuǎn)義(沒有存儲在任何地方)。*/
func unsavedClosure() {
        
        func run(closure: () -> Void) {
            closure()
        }
        
        run {
            self.view.backgroundColor = .red // the closure references 'self'
        }
    }
/*直接將閉包函數(shù)傳遞給closure屬性是很方便的,但會導(dǎo)致控制器內(nèi)存泄漏!
*原因:self被閉包隱式捕獲(在swift中,如UIViewController的viewDidLoad中,可以直接修改view.backgroundColor,而不需要self.view.backgroundColor),self擁有擁有printingButton,從而創(chuàng)建一個引用循環(huán)*/
func setupLeakyButton() {
        printingButton?.closure = printer
    }

func printer() {
        print("Executing the closure attached to the button")
    }
// 需要[weak self]來打破這個循環(huán),即使它會使語法更難看
func setupNonLeakyButton() {
        printingButton?.closure = { [weak self] in self?.printer() }
    }
func printer() {
        print("Executing the closure attached to the button")
    }
/*盡管這個Dispatch是立即執(zhí)行的,但是有一個sempaphore(信號量)阻塞了閉包的返回,并且超時很長。這不會導(dǎo)致泄漏,但會導(dǎo)致延遲釋放“self”,因?yàn)橐胹elf時沒有使用“weak”或“unowned”關(guān)鍵字*/
 func delayedAllocSemaphore() {
        DispatchQueue.global(qos: .userInitiated).async {
            let semaphore = DispatchSemaphore(value: 0)
            print(self.view.description)
            _ = semaphore.wait(timeout: .now() + 99.0)
        }
    }
/*盡管使用了[weak self],這個嵌套的閉包還是會泄漏,因?yàn)榕cDispatchWorkItem關(guān)聯(lián)的轉(zhuǎn)義閉包使用其嵌套閉包的[weak self]關(guān)鍵字創(chuàng)建對“self”的強(qiáng)引用。因此,我們需要將[弱自我]提升一級,到最外層的封閉處(DispatchWorkItem {[weak self] in xxxx }),以避免泄漏*/
func leakyNestedClosure() {
        
        let workItem = DispatchWorkItem {
            UIView.animate(withDuration: 1.0) { [weak self] in
                self?.view.backgroundColor = .red
            }
        }
DispatchWorkItem {[weak self] in xxxx }
        
        self.closureStorage = workItem
        DispatchQueue.main.async(execute: workItem)
    }
// 以下是三種延時釋放的情況,假設(shè)在執(zhí)行DispatchQueue.main.asyncAfter(deadline: .now() + 10)后,未到10秒時self將要釋放
DispatchQueue.main.asyncAfter(deadline: .now() + 10) {
      print(self)// 此時如果將要釋放self,會導(dǎo)致無法立即釋放,因?yàn)殚]包引用了self,而self沒有引用閉包,10秒后,先打印self,后走deinit{}釋放self
}

DispatchQueue.main.asyncAfter(deadline: .now() + 10) { [weak self] in
      print(self)// 此時如果將要釋放self,因?yàn)榇颂幦跻昧藄elf,所以self釋放.先走deinit{},10秒后打印self(此時為nil)
}

DispatchQueue.main.asyncAfter(deadline: .now() + 10) {
      print("Hello word")// 此時如果將要釋放self,因?yàn)闆]有引用self,所以先走deinit{},10秒后打印Hello word
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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