Objective-C: Where to remove observer for NSNotification?

前端 未结 14 1630
北海茫月
北海茫月 2020-11-29 19:37

I have an objective C class. In it, I created a init method and set up a NSNotification in it

//Set up NSNotification
[[NSNotificationCenter defaultCenter] a         


        
14条回答
  •  北海茫月
    2020-11-29 19:54

    Note : This has been tested and working 100% percent

    Swift

    override func viewWillDisappear(animated: Bool){
        super.viewWillDisappear(animated)
    
        if self.navigationController!.viewControllers.contains(self) == false  //any other hierarchy compare if it contains self or not
        {
            // the view has been removed from the navigation stack or hierarchy, back is probably the cause
            // this will be slow with a large stack however.
    
            NSNotificationCenter.defaultCenter().removeObserver(self)
        }
    }
    

    PresentedViewController

    override func viewWillDisappear(animated: Bool){
        super.viewWillDisappear(animated)
    
        if self.isBeingDismissed()  //presented view controller
        {
            // remove observer here
            NSNotificationCenter.defaultCenter().removeObserver(self)
        }
    }
    

    Objective-C

    In iOS 6.0 > version , its better to remove observer in viewWillDisappear as viewDidUnload method is deprecated.

     [[NSNotificationCenter defaultCenter] removeObserver:observerObjectHere];
    

    There is many times its better to remove observer when the view has been removed from the navigation stack or hierarchy.

    - (void)viewWillDisappear:(BOOL)animated{
     if (![[self.navigationController viewControllers] containsObject: self]) //any other hierarchy compare if it contains self or not
        {
            // the view has been removed from the navigation stack or hierarchy, back is probably the cause
            // this will be slow with a large stack however.
    
            [[NSNotificationCenter defaultCenter] removeObserver:observerObjectHere];
        }
    }
    

    PresentedViewController

    - (void)viewWillDisappear:(BOOL)animated{
        if ([self isBeingDismissed] == YES) ///presented view controller
        {
            // remove observer here
            [[NSNotificationCenter defaultCenter] removeObserver:observerObjectHere];
        }
    }
    

提交回复
热议问题