Notice
Recent Posts
Recent Comments
Link
大器晩成
스위프트 메모리 관리 모델 ARC(Automatic Reference Counting) 본문
- Swift는 앱의 메모리 사용량을 추적하고 관리하기 위해 자동 참조 카운팅 (Automatic Reference Counting) (ARC)를 사용합니다.
- Heap 영역에 할당되는 데이터를 메모리에서 해제하기 위해서는 관리가 필요합니다.
- 할당이 해제되지 않으면 메모리 누수(Memory Leak) 현상이 발생합니다.
MRC Model(Object C에서 사용)
- 스위프트에서는 ARC 사용
- 실제 개발자 코드를 보았을 때, point2는 point1을 가리키기고 있기 때문에 RC카운트는 2입니다.
- 이것을 컴파일된 코드로 보면, 내부에 refCount가 있으며 인스턴스트를 생성 시 1이 증가하며, point2가 point1 인스턴스를 할당할 때, 1이 추가됩니다. (retain: 참조카운트 증가)
- 이후 실행이 종료되면 release를 통해 메모리에서 해제합니다.
ARC 동작 (Apple 공식문서)
class Person {
let name: String
init(name: String) {
self.name = name
print("\(name) is being initialized")
}
deinit {
print("\(name) is being deinitialized")
}
}
var reference1: Person?
var reference2: Person?
var reference3: Person?
reference1 = Person(name: "John Appleseed") // RC: 1
// Prints "John Appleseed is being initialized"
reference2 = reference1 // RC:2
reference3 = reference1 // RC:3
reference1 = nil // RC: 2
reference2 = nil // RC: 1
reference3 = nil // RC: 0 //메모리 해제
// Prints "John Appleseed is being deinitialized"
- reference1에 Person 인스턴스를 생성 및 할당하면 초기화와 동시에 RC카운트가 증가합니다
- 동일한 Person 인스턴스를 다른 변수에 할당하면 강한 참조가 설정됩니다.
- 이 시점에서 Person인스턴에스에 대한 3개의 강함 참조가 발생합니다.
- reference1 / reference2에 nil을 할당해도 reference3의 강한 참조가 남아있기 때문에, 클래스는 메모리에서 해제되지 않으며, reference3에 nil을 할당해야 힙 영역에서 인스턴스가 해제됩니다.
[ARC모델의 기반: 소유정책과 참조카운팅]
- 소유정책 - 인스턴스는 하나이상의 소유자가 있는 경우 메모리에 유지됨 (소유자가 없으면, 메모리에서 제거)
- 참조카운팅: 인스턴스를 가리키는 소유자수를 카운팅
참고문헌
https://bbiguduk.gitbook.io/swift/language-guide-1/automatic-reference-counting
자동 참조 카운팅 (Automatic Reference Counting) | Swift
객체의 라이프타임과 관계를 모델링합니다. Swift는 앱의 메모리 사용량을 추적하고 관리하기 위해 자동 참조 카운팅 (Automatic Reference Counting) (ARC)를 사용합니다. 대부분의 경우에 Swift에서 메모리
bbiguduk.gitbook.io
https://developer.apple.com/videos/play/wwdc2016/416/
Understanding Swift Performance - WWDC16 - Videos - Apple Developer
In this advanced session, find out how structs, classes, protocols, and generics are implemented in Swift. Learn about their relative...
developer.apple.com
728x90
'iOS > Swift 문법' 카테고리의 다른 글
캡처리스트 (0) | 2025.03.03 |
---|---|
강함참조 사이클(Strong Reference Cycles Between Class Instances) (0) | 2025.03.03 |
고차함수 (0) | 2025.03.02 |
탈출 클로저(Escaping Closures) / 자동 클로저 (Autoclosures) (0) | 2025.02.28 |
중첩함수 (클로저의 캡처와 동일한 현상) (0) | 2025.02.26 |