The right place to call .removeObserver for NSNotificationCenter = Swift deinit()?

前端 未结 2 851
梦如初夏
梦如初夏 2021-01-17 18:52

I\'ve read a lot of suggestions for the right place to call .removeObserver for NSNotificationCenter since viewDidUnload is not an option.

I was just wondering if t

2条回答
  •  时光说笑
    2021-01-17 19:50

    It really depends on the role of the class where you subscribe to NSNotificationCenter notifications. If you are subscribing in:

    UIView

    Then you should unsubscribe as soon as view gets invisible to the user. To save CPU cycles and not consume resources while user does not see the view.

    UIViewController

    Here it also depends on kind of action that you are going to perform in response to notification. If it is just a UI adjustment that you should unsubscribe as soon as view controller disappears from the screen.

    You App Service layer

    Here it is OK to have .removeObserver inside deinit(). however even here I tend to suggest you to be more explicit about when you subscribe and unsubscribe from NSNotificationCenternotifications and put them in start and stop methods of your service.

提交回复
热议问题