Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Strong Reference Cycle( + 해결법 weak, unowned) #71

Closed
MoSonLee opened this issue Sep 5, 2022 · 0 comments
Closed

Strong Reference Cycle( + 해결법 weak, unowned) #71

MoSonLee opened this issue Sep 5, 2022 · 0 comments

Comments

@MoSonLee
Copy link
Owner

MoSonLee commented Sep 5, 2022

Strong Reference Cycle

  • 상수/ 변수/ 클래스에 인스턴스를 할당 할 때 해당 인스턴스에 대한 강한 참조가 생성됨
  • 예를 들어 두개의 class에서 생성한 변수들을 서로 연결해 주고
  • 그 변수들을 nil로 해제 해주었으면 Rc가 0이 되어야 하는 것 같지만 그 변수들을 갖고 있는 class 들 사이에 참조는 해제되지 않음(이게 강한 순환 참조)
  • ex) class1의 A 변수와 class2의 B 변수를 서로 참조시키면
  • class1.A = class2.B
  • class2.B = class1.A
  • 그리고 class1.A = nil, class2.B = nil
  • 이렇게해도 class1, class2 사이에 참조가 남아있음

해결법: weak, unowned

  • weak
    • 약한 참조
    • RC를 증가 시키지 않은 특징이 있음
    • 예를 들어 아까 class1에서 A 변수를 weak로 선언해주면 강한 순환 참조가 일어나지 않음
    • 참조하는 인스턴스가 메모리에서 해제되면 자동으로 weak 참조를 nil로 설정함
    • 런타임중에 값이 nil로 변경될 가능성이 있으므로 항상 optional, var 타입으로 선언되어야 함
    • 다른 인스턴스의 수명이 더 짧은 경우( 다른 인스턴스를 먼저 할당 해제 할 수 있는 경우)에 사용함

  • unowned
    • weak과 마찬가지로 RC를 증가시키지 않음
    • 다른 인스턴스의 수명이 동일하거나 더 긴 경우 unowned를 사용
    • 참조하는 인스턴스가 메모리에서 해제되어도 자동으로 nil로 변환되지는 않음
    • crash를 발생할 수 있음
    • nil로 변경되지 않으므로 let으로 선언 가능, optional 타입도 지원함(swift 5.0에서 지원하기 시작함)
@MoSonLee MoSonLee closed this as completed Sep 5, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant