I have added an observer in viewDidLoad
and the issues is if I pop back and come to the same class again, it adds observer multiple times.
Below is the code as how observer is being added:
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"PaymentRecieved" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(PaymentRecieved:)
name:@"PaymentRecieved"
object:nil];
}
The notification is being posted from a different view controller after some processes. Below is the code for the same:
ViewController B:
-(void)CardAccepted
{
[[NSNotificationCenter defaultCenter] postNotificationName:@"PaymentRecieved" object:self userInfo:nil];
}
The main issue is removeObserver
is not working. If I pop back 5 times and then push to same screen 5 times then the observer is added and fired all 5 times.
I have tried everything that was available on Stack Overflow but nothing seems to be working. Below are few of the things that I tried:
Trial 1:
BOOL isPaymentObserverAdded = [DefaultsValues getBooleanValueFromUserDefaults_ForKey:@"isPaymentObserverAdded"];
if (!isPaymentObserverAdded) {
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"PaymentRecieved" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(PaymentRecieved:)
name:@"PaymentRecieved"
object:nil];
}
}
[DefaultsValues setBooleanValueToUserDefaults:YES ForKey:@"isPaymentObserverAdded"];
Trial 2:
static dispatch_once_t lock;
dispatch_once(&lock, ^{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(PaymentRecieved:)
name:@"PaymentRecieved"
object:nil];
});
I know there are so many similar questions on SO for the exact same issue but none of them is solving my problem. Apart from this, I also have couple of other notifications set on this screen.
Can somone please help me to understand what I am doing wrong?