Vedaant Arora
Vedaant Arora

Reputation: 217

How to pause timer from appdelegate in xcode and objective c

I am making a game for iPhone and want to be able to pause a timer when a user's game is interrupted like when they hit the home button. I know that in the app delegate there is a method when the app leaves the foreground called:

    - (void)applicationWillResignActive:(UIApplication *)application

What I am struggling with is how to pause the timer. I have a function in my view controller that's called pauseGame and is used for when the user wants to pause the game. I was thinking that it would be easiest to pause the game by using this method. I cannot however understand how to call this method. Any ideas? And sorry for the beginner question.

Upvotes: 0

Views: 1292

Answers (1)

Yogev Shelly
Yogev Shelly

Reputation: 1373

The shortest way is to Use Notifications:

1. define a custom notification, at your application delegate (or anywhere else...)

#define kApplicationWillResignActiveNotification  
@"kApplicationWillResignActiveNotification"

2. dispatch the notification when the applicationWillResignActive: method is called

[[NSNotificationCenter defaultCenter] postNotificationName:
kApplicationWillResignActive object:nil];

3. listen to that notification where ever you want in your project (* import the header file where you @defined the notification)

[[NSNotificationCenter defaultCenter] addObserver:self
selector: @selector(appResigned:) 
name:kApplicationWillResignActiveNotification object: nil];

4. you can get the NSNotification Object if you add it to your selector

-(void)appResigned:(NSNotification *)notification;

Upvotes: 3

Related Questions