0

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

Chesh
  • 179
  • 1
  • 6
  • Please show me the "tap Button" Method. – SGDev Feb 28 '15 at 09:12
  • @SumitGarg add my tab button method. – Chesh Feb 28 '15 at 11:38
  • Reference resources: http://stackoverflow.com/questions/10333153/adding-and-removing-observers-to-nsnotificationcenter-in-a-uiviewcontroller – skyming Feb 28 '15 at 11:38
  • add this line`[[NSNotificationCenter defaultCenter] removeObserver:self name:@"replyPosted" object:nil];` at starting of tab button method. – SGDev Feb 28 '15 at 11:40
  • @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 Feb 28 '15 at 12:02

1 Answers1

0

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

Chesh
  • 179
  • 1
  • 6
  • The solution aforementioned is a little bit tricky. I just use delegation instead of NSNotificationCenter. – Chesh Mar 09 '15 at 03:46