removeObserver with NSNotification… what am I doing wrong?

前端 未结 3 1360
终归单人心
终归单人心 2020-12-28 14:59

Basically, I have a view1 which at some point, calls view2 (via presentModalViewController:animated:). When a certain UIButton in view2 is pressed,

相关标签:
3条回答
  • 2020-12-28 15:44

    If you implement the removal of Observer in the viewWillDisappear: or viewDidDisappear: then you should not leave the addition of the observer in the viewDidLoad.

    Instead put the addition of the observer in the viewWillAppear:. The problem you are having is because when any view is shown onto of the UIViewController view the removal of your observer will occur and since you added observer in viewDidLoad which will happen only once, it will be lost.

    Keep in mind that this approach works well for objects you do not wish to observer while your main view is not in the fore front.

    Also Keep in mind that viewDidUnload has been depreciated too.

    0 讨论(0)
  • 2020-12-28 15:54

    There is nothing wrong putting removeObserver: in dealloc. Just the fact it's not called means view1 not properly releases after dismissing. Looks like something holds pointer to your view1, check for retain cycles.

    Also, you shouldn't call dealloc on super.

    0 讨论(0)
  • 2020-12-28 16:02

    Calling -dealloc doesn't automatically happen after the view controller is dismissed — there can still be some "life" left in the view controller's lifetime. In that timeframe, that view controller is still subscribed for that notification.

    If you remove the observer in -viewWillDisappear: or -viewDidDisappear:, this will have a more immediate effect:

    - (void) viewWillDisappear:(BOOL)animated {
        [super viewWillDisappear:animated];
        [[NSNotificationCenter defaultCenter] removeObserver:self 
                                                        name:@"alert" 
                                                      object:nil];
    }
    
    0 讨论(0)
提交回复
热议问题