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

[Swift] ARC #3

Closed
seungchan2 opened this issue Apr 28, 2022 · 0 comments
Closed

[Swift] ARC #3

seungchan2 opened this issue Apr 28, 2022 · 0 comments
Assignees
Labels

Comments

@seungchan2
Copy link
Owner

seungchan2 commented Apr 28, 2022

ARC

자동으로 메모리 관리를 해줌

객체에 대한 Reference Count 관리하고 0이 되면 해제

런타임에 실행되는 것이 아니라 컴파일 될 때 실행됨

하지만 순환 참조에 유의해야 함

Swift 이전 Objective-C에서는 MRC가 메모리 관리를 했음

retain과 release를 통해 RC를 관리했음

MRC

retain
retain count(= reference count) 증가를 통해 현재 Scope에서 객체가 유지되는것을 보장

release
retain count(= reference count)를 감소시킴.

retain 후에 필요 없을 때 release 함

사실 현재 Swift 에서는 MRC 대신 ARC로 메모리를 관리하기 때문에 이 정도가 있다 정도만 살펴보면 될 듯

class Dog {
    var name: String
    var weight: Double
    
    init(name: String, weight: Double) {
        self.name = name
        self.weight = weight
    }
    
    deinit {
        print("\(name) 메모리 해제")
    }
}


var choco: Dog? = Dog(name: "초코", weight: 15.0)  //retain(choco)   RC: 1
var bori: Dog? = Dog(name: "보리", weight: 10.0)   //retain(bori)    RC: 1


choco = nil   // RC: 0
release(choco)
bori = nil    // RC: 0
release(bori)

간단한 예시를 살펴보겠음

choco bori라는 객체를 하나 찍어냈음

찍어 내는 순간 RC +1이 되는 것임.

과거 Objective-C에서는 retain을 통해 RC를 증가시키고, release를 통해 RC를 감소시켰음

choco bori에 nil값을 줘서 메모리가 해제가 되었고 Dog 클래스 내에 deinit() 메서드가 호출이 됨

ARC모델의 기반

소유정책

인스턴스는 하나이상의 소유자가 있는 경우 메모리에 유지됨
(소유자가 없으면, 메모리에서 제거)

참조카운팅

인스턴스(나)를 가르키는 소유자수를 카운팅

쉽게 말하면, 인스턴스를 가르키고 있는 RC가 1이상이면 메모리에 유지되고, 0이되면 메모리에서 제거됨

이게 ARC의 기본 동작 원리임

@seungchan2 seungchan2 changed the title [Memory] 메모리의 영역과 기능 [Swift] ARC란? Apr 28, 2022
@seungchan2 seungchan2 changed the title [Swift] ARC란? [Swift] ARC May 20, 2022
@seungchan2 seungchan2 self-assigned this May 20, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant