Reputation: 392
I have a view controller "A" which is registered as an observer like this,
-(void)viewWillAppear:(BOOL)animated
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"localActionTaken" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveLocalActionNotification:) name:@"localActionTaken" object:nil];
}
I am also removing observer in dealloc method.
From view controller "A" user goes to view controller "B" where "localActionTaken" notification is posted.
Everything works fine till this
Now I have another view controller "C" from which user is pushed to view controller "A" and from "A" to "B". But the issue is in this "C"->"A"->"B", if notification is triggered in "B" then observerver "A" is notified twice!
Please let me know if I am missing here anything.
Note : I am using ECSlidingview and "A" and "C" are top view controllers.
----------------- Update -----------------
I had to move removeObserver to viewWillDisappear based on check for specific view controllers in stack.
Upvotes: 0
Views: 125
Reputation: 7963
Add the observer in viewDidLoad
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveLocalActionNotification:) name:@"localActionTaken" object:nil];
}
Upvotes: 0
Reputation: 8247
An important thing you forgot it is that you need to be symmetric
in your class.
If you add the notification in the init
method, you will remove the notification in the dealloc
method.
If you add the notification in the viewWillAppear
method, you will remove the notification in the viewWillDisappear
method (as @Spetruk said in a comment).
So, you can do :
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveLocalActionNotification:) name:@"localActionTaken" object:nil];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"localActionTaken" object:nil];
}
Upvotes: 0
Reputation: 1536
Does the number of notifications observed accumulate (grow beyond twice) when navigating between A and B. The viewWillAppear will keep getting called when moving from A <-> B but the dealloc will not be called yet. So perhaps there is something wrong the removeObserver in viewWillAppear that is leading to multiple observers being added on A and this would cause multiple notifications to be observed. The code sample you have included seems to work for adding and removing and in dealloc when popping back to C but I haven't tried with "ECSlidingview"
Upvotes: 1