Open Phangg opened 2 weeks ago
[ Low Memory Warning 에 대한 공식문서 자료 ]
applicationDidReceiveMemoryWarning(_ application: UIApplication)
라는 메서드가 있는데, 앱이 메모리 부족 상태가 될 때 트리거 됨
func applicationDidReceiveMemoryWarning(_ application: UIApplication) {
// 메모리 부족 시 수행할 작업 수행 ( 재생성 가능한 리소스 제거 등 )
}
didReceiveMemoryWarning()
는 ViewController 에 있는 메서드로 동일하게, 앱이 메모리 부족 상태가 될 때 트리거 됨
class MyViewController: UIViewController {
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// 메모리 부족 시 수행할 작업 수행
}
}
didReceiveMemoryWarningNotification
는 NotificationCenter 에서 사용 할 수 있음
struct MemoryMonitor {
init() {
NotificationCenter.default.addObserver(forName: UIApplication.didReceiveMemoryWarningNotification,
object: nil,
queue: nil) { notification in
// ...
}
}
}
DISPATCH_SOURCE_TYPE_MEMORYPRESSURE
는 Memory Pressure 를 모니터링하는 DispatchSource ...🤕
warning, critical, normal, all
4가지의 조건을 통해, 메모리 부족 상태를 구분할 수 있음
class MemoryPressureMonitor {
static let shared = MemoryPressureMonitor()
private let dispatchSource = DispatchSource.makeMemoryPressureSource(eventMask: [.warning, .critical])
private init() {
dispatchSource.setEventHandler { [weak self] in
if let event = self?.dispatchSource.data,
self?.dispatchSource.isCancelled == false {
switch event {
case .warning:
print("MemoryPressureMonitor: Low memory warning")
case.critical:
print("MemoryPressureMonitor: Critical memory warning")
default:
print("MemoryPressureMonitor: Unknown Event")
}
}
}
dispatchSource.activate()
}
deinit {
dispatchSource.cancel()
}
}
메모리 최적화는 앱의 성능, UX 에 직접적인 영향을 미치게 됨
메모리 누수를 방지하고, 백그라운드 상태일 때 효율적으로 관리하도록 설계해야 함
Xcode 의 Instruments 도구를 활용 ( command + i 를 눌러서, 실행 / Leaks 에서 메모리 누수 확인 )
ARC (Automatic Reference Counting) 를 활용 ( 메모리 누수 방지 )
이미지 등 리소스 파일 사용 최적화 ( 필요한 해상도의 이미지만 로드 / 사용하지 않는 이미지 리소스 해제 등 )
메모리 경고 대응 전략 필요 ( 앱의 강제 종료를 막기 위함 )
Clean
or Drity
Memory Compressor
를 사용 ( iOS 7 도입 )
( *Memory Compressor : 아직 엑세스 되지 않은 페이지를 압축하여, 공간을 많이 사용하지 않도록 함. 메모리를 엑세스 할 때 압축 해제 )didReceiveMemoryWarning()
메서드를 사용하여, warning 이 트리거 되었을 때, 모든 캐시를 지우는 것이 좋을까? 그렇지 않음NSCache
를 사용하면, 여러 쓰레드에서 동시 접근해도 안전 ( thread safe )EXC_RESOURCE_EXCEPTION
)
iOS 앱의 낮은 메모리 상황 대응 방안과 관련 API에 대해 설명해주세요.