Reputation: 37
I am using this function in my view controllers to recognize if the app is active again and to refresh some data:
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(becomeActive:)
name:UIApplicationWillEnterForegroundNotification
object:nil];
This works for refreshing after getting active, but everytime the app gets back from background to foreground (inactive to active) it calls the function one more time.
So if I closed and opened the app 4 times, the function will be called 4 times!
EDIT: The function will be called this way:
But it only have to be called 1 time after getting back in foreground. In some situation the app have to show an alert view after getting active and checking data. This alert view will be shown 4 times when the function will be called 4 times.
In the app delegate this function does nothing, but it is mentioned.
I am using Xcode 4.2 and iOS 5! I also used UIApplicationDidBecomeActive
, but it also cause the same problem.
Upvotes: 2
Views: 7811
Reputation: 37
No i solved my problem.
The method which is called through the observer will not call the viewDidLoad
anymore. so the viewDidLoad
will only called once (on first application start up).
The function getActive
which will be called through the observer now calls the methods which were firstly called out of the viewDidLoad
.
I also put the removeObserver
function to the viewDidLoad
, which will only be called, if the user will stop the app completely.
Thanks for the ideas and the help! Now i know a little bit more about making a multi-tasking app.
Upvotes: 0
Reputation: 494
i think you should remove addObserver in viewWillDisappear method. it is working for me.
- (void)viewWillDisappear:(BOOL)animated
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
Upvotes: 0
Reputation: 2593
I don't know at when your adding self as an observer, but every time the app becomes active, you seem to be adding self as an observer, again and again. Thus the multiple calls.
You must only add your view controller as an observer once. Try using the controllers init: method. And, ensure that you remove the view controller as an observer in the dealloc: method.
Upvotes: 9
Reputation: 14160
That's actually what this notification is supposed to do. If you need to be notified when application is started, use applicationDidFinishLaunching.
Upvotes: 0