xonegirlz
xonegirlz

Reputation: 8977

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?

Upvotes: 13

Views: 9046

Answers (3)

janusfidel
janusfidel

Reputation: 8106

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];

Upvotes: 7

Apurv
Apurv

Reputation: 17186

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.

Upvotes: 27

Bill Wilson
Bill Wilson

Reputation: 954

It is possible if you have added the same observer multiple times for the newsfeedFetchCompleted notification. You should match your addObserver calls with removeObserver calls.

For example if you added the observer in viewWillAppear/viewWillDidAppear/ViewDidLoad of a UIViewController, you should remove it in viewWillDisappear/viewDidDisappear/ViewDidUnload.

The corresponding remove call for addObserver, is removeObserver:name:object:

More info can be found in the NSNotificationCenter docs

Upvotes: 2

Related Questions