Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSNotificationCenter one post causes observers to be called twice

I have the following code:

 [[NSNotificationCenter defaultCenter] postNotificationName:kNewsfeedFetchCompleted object:self userInfo:userinfo];

only this, no where else. And here's how I set the observer:

  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(newsfeedFetchCompleted:) name:kNewsfeedFetchCompleted object:nil];

question is when I do one post the newsfeedFetchCompleted is called twice.. how is this even possible?

like image 806
xonegirlz Avatar asked Jun 29 '12 05:06

xonegirlz


2 Answers

This is possible when your code for addObserver is executed twice. The notification function will be called as many times as it is registered.

So make sure your code for adding observer is executed for once only. So, you can keep it in viewDidLoad or init method.

If you are putting it in viewWillAppear then remove observer in viewWillDisAppear.

like image 148
Apurv Avatar answered Sep 27 '22 23:09

Apurv


before you add observer, make sure you remove the previous observer added.

[[NSNotificationCenter defaultCenter]removeObserver:self];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(newsfeedFetchCompleted:) name:kNewsfeedFetchCompleted object:nil];
like image 29
janusfidel Avatar answered Sep 27 '22 22:09

janusfidel