0
votes

I have a tab-bar app with multi ViewControllers and embed them in some nav controllers. I googled and tried adding observer to the first detailVC's viewDidLoad / viewWillAppear / viewDidAppear and remove observer in the related viewWillDisappear / viewDidDisappear perform a model segue to my second detailVC(also embed in a nav controller) where i tap a button called postNotification then dismiss the second detailVC the custom selector function gets called it works fine. If i tapped back to the masterVC did the above procedure again the function gets called two times and so on.

BTW I follow this protocol when adding observer.

[[NSNotificationCenter defaultCenter] removeObserver:self name:@"replyPosted" object:nil]; 
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addNewComment:) name:@"replyPosted" object:nil];

tap button methods

[self dismissViewControllerAnimated:YES completion:nil];
NSDictionary *userinfo = @{@"reply_id":[result valueForKey:@"reply_id"],@"comment":comment};
[[NSNotificationCenter defaultCenter] postNotificationName:@"replyPosted" object:self userInfo:userinfo];

Update!

Problem solved by checking the first DetailVC in the navigation stack and add few lines in viewWillDisappear

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    NSLog(@"%@",self.navigationController.viewControllers);
    //to check currentVC in navigation stack or not
    if([self.navigationController.viewControllers indexOfObject:self] == NSNotFound){
        NSLog(@"remove observer from viewWillDisappear");
        [[NSNotificationCenter defaultCenter] removeObserver:self name:@"replyPosted" object:nil];
    }   
}

chart

1
Please show me the "tap Button" Method. - SGDev
@SumitGarg add my tab button method. - Chesh
add this line[[NSNotificationCenter defaultCenter] removeObserver:self name:@"replyPosted" object:nil]; at starting of tab button method. - SGDev
@SumitGarg it does't work. i put adding observer code in viewWillAppear if i add remove observer in viewWillDisappear ,my selector function will never get called. I just wondered why this line in the adding observer doesn't work [[NSNotificationCenter defaultCenter] removeObserver:self name:@"replyPosted" object:nil]; - Chesh

1 Answers

0
votes

In viewWillDisappear do nothing if the first detailVC is in the navigation controller stack, otherwise remove the observer.