반응형
250x250
05-19 01:14
Today
Total
«   2026/05   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
Notice
Recent Posts
Recent Comments
Link
Archives
관리 메뉴

Bill Kim's Life...

[iOS] iOS 메모리 누수의 핵심 — Retain Cycle 한 번에 끝내기 본문

DEV Tips/iOS

[iOS] iOS 메모리 누수의 핵심 — Retain Cycle 한 번에 끝내기

billnjoyce 2026. 3. 22. 20:44
728x90
반응형

개요

iOS에서 가장 많이 놓치는 문제:

객체가 해제되지 않음 (deinit 안 호출됨)


의미

  • 메모리가 계속 쌓임
  • 앱 성능 저하
  • 심하면 크래시 발생

주요 원인:

  • 객체끼리 서로 강하게 참조 (strong reference)

문제 코드

class ViewController: UIViewController {

    var closure: (() -> Void)?

    override func viewDidLoad() {
        super.viewDidLoad()

        closure = {
            self.view.backgroundColor = .red // ❌ retain cycle 발생
        }
    }

    deinit {
        print("deinit") // 호출 안 됨
    }
}

문제:

  • closure가 self를 강하게 참조
  • self도 closure를 가지고 있음

→ 서로 놓지 않음 (메모리 누수)


해결 코드

방법 1: weak 사용 (가장 기본)

closure = { [weak self] in
    self?.view.backgroundColor = .red
}

방법 2: unowned 사용 (확실한 경우만)

closure = { [unowned self] in
    self.view.backgroundColor = .red
}

주의:

  • self가 먼저 해제되면 크래시 발생

방법 3: deinit으로 확인

deinit {
    print("deinit 호출됨 ✅")
}

이게 안 찍히면 100% 누수


🎯 한 줄 정리

메모리 누수 = 서로를 강하게 잡고 있음 → weak로 끊어라

728x90
반응형
Comments