Programming/Mac & iOS

[iOS] Autorelease Pool과 메모리 관리

MB Brad KWON 2017. 8. 19. 15:30

    Autorelease pool은 객체가 즉시 해제되는 가능성을 피하고자 할 때, 객체에 대한 소유권을 포기하도록 하는 메카니즘이다. autorelease pool은 '@autoreleasepool'이라는 키워드로 사용한다. 블록안 에서 autorelease 메시지를 받은 객체들은 '@autoreleasepool'로 선언한 블록의 끝에서 release 메시지를 받는다. 일반적으로 autorelease 메시지는 객체를 할당한 구역 밖에서 객체를 해제하고자 할때, 컴파일러에게 이를 알리고자 사용하는 메시지이다. 하지만 autorelease 메시지는 객체가 언제 해제되는지 불명확해 진다. autorelease pool은 이런 autorelease 객체가 해제되는 시점을 명시적으로 보여준다. 즉 autorelease pool안에서 생성된 autorelease 객체들은 autorelease pool에서 벗어나는 시점에 해제된다. 아래는 non-ARC 환경과 ARC 환경에서 autorelease pool이 가지는 매커니즘에 대한 예시이다.





    그럼, autorelease pool은 언제 사용이 될까? 우선 기본적으로 우리가 사용하는 모든 autorelease 메시지에는 autorelease pool이 연관되어 있다. macOS/iOS 앱을 개발하면 기본적으로 Foundation framework를 사용한다. Foundation framework는 autorelease pool로 감싸져 있다. autorelease 메시지를 받은 객체들은 이 autorelease pool이 해제될때, 같이 해제된다. 이처럼 framework 내부에서 사용되는 autorelease 객체를 관리하기 위해 사용된다.