简体   繁体   中英

How to stop UIDynamicAnimator in applicationDidEnterBackground

How can I stop a UIDynamicAnimator when applicationDidEnterBackground is called? Also, how can I start the timer in applicationWillEnterForeground ? Here's the code I have:

in my game viewcontroller.m

 -(void)stoptime
{
     [_animator removeAllBehaviors]; //_animator is my UIDynamicAnimator
      [time invalidate];
}

in my app delegate.m

- (void)applicationDidEnterBackground:(UIApplication *)application
{
       gameViewController *new=[[gameViewController   alloc]initWithNibName:@"gameViewController" bundle:nil];
    [new stoptime];
}

Use NSNotificationCenter . In your view controller, listen for notifications (in viewDidLoad ):

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stoptime) name:@"StopTimeNotification" object:nil];

Then, in your applicationDidEnterBackground:

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"StopTimeNotification" object:nil];
}

Finally, in your stoptime method:

-(void)stoptime {

    [_animator removeAllBehaviors]; //_animator is my UIDynamicAnimator
    [time invalidate];
    time = nil;
}

Be sure to call the following when your view controller is about to be freed:

[[NSNotificationCenter defaultCenter] removeObserver:self];

Two additional comments:

1 - When invalidating a timer, it's good practice to set it to nil as well so you can reuse it later

2 - Don't use new as a name for any variable, it's a reserved keyword.

EDIT

You can use a similar method for restarting your timer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM