-
UIView 가 사라지는 타이밍은? like viewDidDisappeariOS 2025. 4. 25. 18:44반응형
WKWebView처럼 뷰가 사라질 때 작업들을 해줘야 하는 경우가 있습니다.
UIViewController 에선 다양한 lifeCycle 메서드를 제공합니다.
따라서 viewWillDisappear, viewDidDisappear 를 비롯해 원하는 타이밍에 필요한 작업을 해줄 수 있습니다.하지만 UIView는 이런 lifeCycle 메서드를 세밀하게 제공해 주지 않습니다.
그래서 보통 deinit 에서 해주곤 했었는데요.Swift 에서 isolated 개념이 강화되면서 deinit 에서 self를 참조할 수 없어 곤란한 상황들이 있습니다.
deinit 에서도 캡처를 통해 기존처럼도 사용할 수 있지만, 메모리 이슈가 생길 위험이 있다고 생각이 들었습니다.
그래서 뷰가 제거되는 좀 더 안전한 타이밍을 찾아보았습니다.# didMoveToWindow
저는 익숙하지 않았던 메서드인데요. 찾아보니 이런 메서드를 제공합니다.
The default implementation of this method does nothing. Subclasses can override it to perform additional actions whenever the window changes.
The window property may be nil by the time that this method is called, indicating that the receiver does not currently reside in any window. This occurs when the receiver has just been removed from its superview or when the receiver has just been added to a superview that is not attached to a window. Overrides of this method may choose to ignore such cases if they are not of interest.여기서 window를 확인해 nil 이라면 뷰가 제거 되었다고 볼 수 있을 것 같습니다.
따라서 아래처럼 사용하면 더 안전하게 처리할 수 있습니다.// UIView override func didMoveToWindow() { super.didMoveToWindow() if window == nil { // ... } }
반응형'iOS' 카테고리의 다른 글
[Swift6] WebView 에서 워닝이 발생할 때 (0) 2025.04.25 XcodeMacro 헤더 주석 변경하기 (1) 2025.01.22 내 앱의 Crashlogs 확인하기 (dSYM은 뭔가?) (0) 2025.01.17 Preference (PreferenceKey) (0) 2024.11.24 [iOS] OSSignpost > 특정 작업의 duration 측정하기 (0) 2024.07.01