NSNotificationCenter with respect to ViewWillAppear and ViewWillDisapper

前端 未结 2 1648
南笙
南笙 2021-01-15 13:34

I have a simple viewController that I want to listen for UIKeyboardWillHideNotification. Therefore I have the following code:

- (void) viewWill         


        
2条回答
  •  醉话见心
    2021-01-15 13:56

    Registering the notification in viewWillAppear and unregistering it in viewWillDisappear seems to be a clean and symmetric solution to me.

    Note that viewWillAppear can be called multiple times before dealloc (e.g. if another view controller is pushed onto your VC, or if you switch between tab bar controllers.) If you register the notification in viewWillAppear and unregister it only in dealloc then you will get duplicate registrations (compare Warning for iOS/iPhone users about duplicate NSNotification observations) and the registered selector is called multiple times for a single notification event.

    I actually prefer the block-based observer registration method

    addObserverForName:object:queue:usingBlock:
    

    which returns an opaque object which is used for removing the observer again. Storing this return value into an instance variable of your view controller helps to keep track if the observer is already registered or not, and therefore helps to avoid duplicate registrations.

提交回复
热议问题