iOS/Swift

[Swift] Retain Cycle

차니 ☻ 2021. 12. 7. 15:43

1. Retain Cycle

Retain Cycle이란 메모리가 해제되지 않고 유지되어 메모리 누수가 발생하는 현상을 말합니다.

클래스간 참조는 default로 강한(strong) 참조이기 때문에 각각의 클래스에서 참조가 발생한다면 강한 참조로 인해 메모리에서 해제되어야 할 상황에도 해제되지 않는 현상이 발생합니다.

이는 곧 메모리 누수(Memory Leak)로 이어집니다

 

2. Delegate

2-1. delegate를 weak var로 선언해야하는 이유

Retain Cycle이 발생하기 때문입니다.

이러한 상황을 방지하고자 하는 것이 delegate 참조 수준을 weak로 낮추는 방법입니다.

2-2. weak var 적용

적용 전 코드

import UIKit

protocol CustomDelegate {
    func returnValue(vc: BViewController, text: String?)
}

class BViewController: UIViewController {
    
    var delegate: CustomDelegate!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

 

적용 후 코드

import UIKit

protocol CustomDelegate: AnyObject {
    func returnValue(vc: BViewController, text: String?)
}

class BViewController: UIViewController {
    
    weak var delegate: CustomDelegate?
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

 

3. Closure

Delegate와 마찬가지로 클로저에서도 Retain Cycle이 발생합니다

해결 방법 또한 참조 수준을 strong에서 weak로 낮추어 사용하는 방식입니다

 

https://vuralkaan.medium.com/closure-retain-cycle-in-swift-8699fcd7929a

 

Closure Retain Cycle in Swift

Before you begin I highly recommend you to check ARC story.

vuralkaan.medium.com

https://bongcando.tistory.com/20

 

[Swift] 클로저에서의 weak self 에 대해 알아보자

클로저를 사용하면서 weak self를 사용해본 경험이 있거나, weak self를 사용하는 코드를 본 적이 있을 것이다. weak self 를 왜 사용해야 하고, 언제 사용해야 하는지에 대해 알아보자. 1. weak self를 왜

bongcando.tistory.com

 

4. 메모리 누수는 어떻게 찾을 수 있을까?

deinit {
	print("deinit..")
}

클래스가 메모리에서 해제될 때 deinit() 메서드가 호출되므로 해당 메서드를 통해 확인해 볼 수 있습니다.