开发者

App Delegate - Unload View Controller

I'm trying to unload a view controller from view when the iPhone goes to sleep. My app has a stopwatch that has to keep counting when the phone goes to sleep or call comes in or the user closes the app without logging out.

I have all this functionality in place, I'm capturing all start times and stop times and upon re-entering the stopwatch view controller, I calculate the difference. It all works beautifully. When I was doing some additional testing I realised I hadn't catered for the iPhone going into sleep mode.

So all I need to do to make sure my stopwatch is correct bring the user back to the app home screen. I know the following method is called when the app goes to sleep:

-(void)applicationWillResignActive:(UIApplication *)application

How do I unload the stopwatch view controller from my app delegate ?

---- UPDATE ----

kpower, thanks for your feedback. I've implemented the following code:

In my App Delegate:

- (void)applicationWillResignActive:(UIApplication *)application
{
    [[NSNotif开发者_如何学GoicationCenter defaultCenter] postNotificationName:@"AppIsAsleep" object:nil];
}

In my view controller, I have the following:

-(void)viewDidLoad 
{   
    // Add Observer.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewDidUnload:) name:@"AppIsAsleep" object:nil];
}

- (void)viewDidUnload {
    //Remove the Observer.
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"AppIsAsleep" object:nil];
}

When the phone goes to sleep, it actually closes the app, am I doing something wrong ?

Regards, Stephen


You can use the Notifications mechanism. It allows you to unload view controller from different place (not the AppDelegate) this case.

For example, in your view controller's viewDidLoad method you add an observer (don't forget to remove it in viewDidUnload) and in applicationWillResignActive: method of AppDelegate you just simply post notification. That's all.

↓ Update here ↓

When you get a notification - you should manage view controller's removing by yourself. And calling viewDidUnload here is not the solution, cause this method is called after view controller was already unloaded and doesn't cause removing.

How to remove? Depends on how the view controller was added (for example, popViewControllerAnimated for UINavigationController). The main idea here is to make object's retain count equal to 0 (as you know this case an object will be destroyed) - so you should sent release message necessary amount of times.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜