주로 autoreleasepool을 자동으로 관리해주지 않는 Operation Queue에서 많이 사용합니다.
autoreleasePool에 포함된 객체들은 코드가 autoreleasePool에서 벗어나면 한번에 참조 카운트가 줄어듭니다.
func useManyImages() {
let filename = pathForResourceInBundle
for _ in 0 ..< 5 {
for _ in 0 ..< 1000 {
let image = UIImage(contentsOfFile: filename)
}
}
}
이와 같이 여러개의 UIImage가 생성되는 케이스가 있다고 해봅시다.
이 경우 매번 UIImage가 생성될때마다 retain이 발생하고 이들이 release되는 것은 함수가 종료된 후입니다.
그에 따라 프로그램 메모리 allocation graph가 함수종료 전까지 상승합니다.
func useManyImages() {
let filename = pathForResourceInBundle
for _ in 0 ..< 5 {
autoreleasepool {
for _ in 0 ..< 1000 {
let image = UIImage(contentsOfFile: filename)
}
}
}
}
하지만 autoreleasepool을 사용하면 autoreleasepool의 block이 종료되면서 내부 객체들의 메모리가 해제됩니다.
이에 따라 프로그램 메모리 allocation graph는 autoreleasepool의 block이 종료되기 전까지만 늘어나고 바로 줄어들게 됩니다.