This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
How can I programmatically pause an NSTimer?
I have a question. How can I pause a countdown using a timer? I am developing a game. In the game, I need to go to next view when the timer pauses, and after coming back I want to resume it.
I try this code in the view:
[mytimer pause];
// to resume
[mytimer resume];
I try that code, but I get a warning saying: "NSTimer may not respond to 'pause'"
I build with that warning and when I press the pause button, the app crashes.
NSTimer indeed doesn't have resume and pause methods so you can end up with a crash in runtime after such a warning. Generally you can create 2 kinds of timers (see NSTimer class reference) one that implements only once and the second, that repeats. Example:
This way you create a timer, that will enter callback myMethod each second.
NSTimer *myTimer = [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:#selector(myMethod:)
userInfo:nil
repeats:YES];
You probably will choose this one for your purpose where in your class you should maintain some
BOOL pausevariable and in the callback myMethod do the following:
- (void) myMethod:(NSTimer *) aTimer
{
if (!pause) {
// do something
// update your GUI
}
}
where you update pause accordingly somewhere in your code.
To stop the timer (and release it) call
[myTimer invalidate];
good luck
What you want, is what OpenGLES application brings up to you. You should create 2 methods like this:
- (void)startAnimation
{
self.animationTimer = [NSTimer scheduledTimerWithTimeInterval:animationInterval target:self selector:#selector(selector) userInfo:nil repeats:YES];
}
- (void)stopAnimation
{
[animationTimer invalidate];
animationTimer = nil;
}
It's something like this.
Refer to the NSTimer Class Reference, there is no pause method.
Related
This is what I want to do:
I want a timer, to fire a method and then, in the end of this method, be toggled off, and turn on an other timer on another method, and then entering a loop.
So what are the codes used to toggle between on and off the timer on a method?
In Delphi I use:
timer.enable:=True; // timer.enable:=False;
Are there a similar way to do it on objective-c?
I'm using Xcode 4.4
Thanks!
To turn the timer off, call invalidate on your timer like so:
[yourTimer invalidate]
And then to start a new one:
NSTimer *newTimer;
newTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 //Every how many seconds
target:self
selector:#selector(methodToCall)
userInfo:nil
repeats:YES];
Assuming your NSTimer is called "timer", you can use...
[timer invalidate]
to stop the timer. To make a timer pass a message to it's target method instantly, use
[timer fire]
To start a timer, you use one of the constructor methods listed in the documentation (https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nstimer_Class/Reference/NSTimer.html) such as
NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:#selector(doThisWhenTimerFires:) userInfo:nil repeats:NO]
- (void)doThisWhenTimerFires:(NSTimer *)timer
{
//code here
}
Iam displaying time in my application using NSTimer Class starting with 00:00.00 (mm:ss.SS) when my application launched. I want to terminate my application when time reaches to 75:00.00 (mm:ss.SS) in iPhone.
The below code snippet will do the work for you. But its not recommended to use the exit() method to quit the app as it will appear that the app has been crashed to the end user. I recommend you to show an alert after 75 mins and ask the user to quit the app.
[NSTimer scheduledTimerWithTimeInterval:270000
target:self
selector:#selector(quitTheApp)
userInfo:nil
repeats:NO];
- (void)quitTheApp
{
exit(0);
}
Once you start the timer,immediately next line call the below method:
[self performSelector:#selector(stopTimer) withObject:nil afterDelay:75.0];
And stopTimer method should be like this:
-(void) stopTimer
{
[timer invalidate];
timer = nil;
}
I'm trying to develop a game and running into a small issue with NSTimer, once a sprite appear it has a certain amount on time in my scene before fading out.
double CALC_TIME = 5;
[NSTimer scheduledTimerWithTimeInterval:CALC_TIME target:self selector:#selector(hideSprite) userInfo:nil repeats:NO];
I want hideSprite to be called after 5 seconds, but instead it's called instantly(Or near instant).
A possible solution:
I know I could do this by setting the timer to repeat, and having a bool firstCall that is set first time and then the next interval the fading is done, the timer is invalidated but I don't think this is good practice
Like this:
bool firstCall = false;
-(void)hideSprite{
if(!firstCall){
firstCall = true
}else{
//fade out sprite
//Invalidate NSTimer
//firstCall = false;
}
}
Thanks for your help!
I suspect something else is calling hideSprite. The code you have written will cause the timer to wait for five seconds before calling the selector hideSprite.
Provide a different selector (write a new test method which just does an NSLog) to the timer and see what happens. This will tell you a) whether the timer is indeed immediately firing and b) if something else is calling hideSprite.
[NSTimer scheduledTimerWithTimeInterval:CALC_TIME target:self selector:#selector(testTimer) userInfo:nil repeats:NO];
-(void) testTimer { NSLog(#"Timer - and only the timer - called me."); }
-(void) hideSprite {
NSLog(#"I definitely wasn't called by the timer.");
}
Quite often it's easier to just use something like
[UIView animateWithDuration: 0 delay: 5 options:0 animations: nil completion:
^{
// fade sprite
}];
(not sure if animations can be nil, but you get the idea).
Consider initializing your timer using the initWithFireDate:interval:target:selector:userInfo:repeats method. Here is a more detailed look at NSTimer.
I want to produce a delay of 2 seconds using NSTimer how to initialize timer in program?
Multiple options here.
If you just want a delay of 2 seconds you could use the sleep() function
#include<unistd.h>
...
sleep(2);
Or you may be able to use NSTimer like so
[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:#selector(fireMethod) userInfo:nil repeats:NO];
And in your class you would have a method defined as
-(void)fireMethod
{
//Do stuff
}
Here you go...
[NSTimer scheduledTimerWithTimeInterval:2
target:self
selector:#selector(action)
userInfo:nil
repeats:NO];
Simple answer: [NSThread sleepForTimeInterval:10.0];
Note that you should not really be thinking about delays in an event driven UI/OS. You should thinking about tasks you want to do now, and tasks you want to do later, and code these subtasks and schedule them appropriately. e.g. instead of:
// code that will block the UI when done in the main thread
- (void) methodC {
doA();
delay(2);
doB();
}
you might want to have code that looks more like:
- (void) methodA {
doA();
return; // back to the run loop where other useful stuff might happen
}
- (void) methodB {
doB();
}
and you can then schedule methodB with an NSTimer at the end of methodA, an NSTimer started by whatever called methodA, or, the best option, by the asynchronous completion routine of something started by methodA.
I've been using an NSTimer successfully, but am now having trouble with it. Undoubtably something stupid. Appreciate another set of eyes. Running the debugger, I see that applicationDidFinishLaunching is called, but trigger is never called.
-(void) trigger:(NSTimer *) theTimer{
NSLog(#"timer fired");
}
- (void)applicationDidFinishLaunching:(UIApplication *)application {
nst = [NSTimer timerWithTimeInterval:1.0 target:self selector:#selector(trigger) userInfo:nil repeats:YES];
[window makeKeyAndVisible];
}
The selector must have the following signature:
- (void)timerFireMethod:(NSTimer*)theTimer
so you need
#selector(trigger:)
--edit--
Maybe you are doing this somewhere else, but in the code you included you do not actually start the timer. You have to add it to a NSRunLoop before it can trigger any events at all.
[[NSRunLoop currentRunLoop] addTimer:nst forMode:NSDefaultRunLoopMode];
If I read the examples correctly. I've only used the one the init method that automatically adds it to the current NSRunLoop. You really should look at the developer docs that someone included in the comments to my post.
Two things:
1) as others say, the method should have the following signature..
-(void) trigger:(NSTimer *) theTimer;
and you make the timer thus:
nst = [NSTimer timerWithTimeInterval:1.0 target:self selector:#selector(trigger:) userInfo:nil repeats:YES];
2) merely creating the timer does not run it. As the documentation says:
You must add the new timer to a run
loop, using addTimer:forMode:. Then,
after seconds have elapsed, the timer
fires, invoking invocation. (If the
timer is configured to repeat, there
is no need to subsequently re-add the
timer to the run loop.)
Here's a piece of real functioning code that you can model after. The timer creation is the same as yours, but it also adds it to runloop the right way.
[[NSRunLoop currentRunLoop] addTimer:
[NSTimer timerWithTimeInterval:0.1
target:self
selector:#selector(someSelector:)
userInfo:nil
repeats:NO]
forMode:NSDefaultRunLoopMode];
The selector you're giving the timer, trigger, indicates that it should call a method that takes no parameter. Either change your timer-fired method to
- (void)trigger
{
// look at me, I don't take any parameters
NSLog(#"timer fired");
}
or change your initial timer call to use #selector(trigger:).
Your problem is due to the fact that timerWithTimeInterval:target:selector:userInfo:repeats: creates a timer but does not schedule it on the run loop, you have to do it yourself.
However, you may as well use this method which creates the timer and schedules it on the run loop: scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:
I had a problem when starting timer in - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { not in main thread.
dispatch_async(dispatch_get_main_queue(), ^{
[self startScheduledTimer];
});