[Swift] Retain cycle, weak, unowned [번역]

1. How does memory management work in Swift?

→ 최소 하나의 강한참조가 있는 한 해당 객체의 메모리는 해제되지 않는다.

2. What is Retain Cycle?

ex) 강한참조로 메모리 누수 발생

class TestClass{
    var testClass: TestClass? = nil
    init(){
        print("init")
    }
    deinit(){
        print("deinit")
    }
}

// 두 변수가 같은 TestClass 클래스를 강한참조
var testClass1: TestClass? = TestClass()
var testClass2: TestClass? = TestClass()

testClass1?.testClass = testClass2
testClass2?.testClass = testClass1

→ 두 TestClass 클래스의 객체는 서로를 가리키게 된다.

→ 이후 두 변수(testClass1, testClass2)에 nil을 할당해도 메모리에서 해제되지 않음. (메모리 누수)

3. Weak

ex) weak를 통해 Retain Cycle 해결

class TestClass{
    weak var testClass: TestClass? = nil  // 이제 이 참조는 약한 참조이다!
    init(){
        print("init")
    }
    deinit(){
        print("deinit")
    }
}

var testClass1: TestClass? = TestClass()
var testClass2: TestClass? = TestClass()

testClass1?.testClass = testClass2
testClass2?.testClass = testClass1

testClass1 = nil
testClass2 = nil

→ weak reference는 참조는 할 수 있지만 Reference Count가 증가되지 않음.

→ 객체 메모리 해제되면 그에 대응하는 변수는 자동으로 nil

(optional 타입만이 nil 값 가능, 그러므로 모든 weak 참조 변수는 반드시 optional 타입)