how to make NSTimer consistent on xcode - ios

I'm making a game and would like to use a timer to countdown an event, just like what's seen on Bejeweled. I know that I've to put NSTimer in a NSRunLoop to make it work, since NSTimer is inaccurate. Have tried the following but it still don't work. Please help!
#import ...
NSTimer *_gameTimer;
int secondsLeft;
//some code
//called countdownTimer using [self countdownTimer];
- (void)countdownTimer
{
_gameTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(updateTime:) userInfo:nil repeats:YES];
NSRunLoop *gameRun = [NSRunLoop currentRunLoop];
[gameRun addTimer:_gameTimer forMode:NSDefaultRunLoopMode];
}
- (void)updateTime:(NSTimer *)timer
{
if (secondsLeft>0 && !_gameOver) {
_timerLabel.text = [NSString stringWithFormat:#"Time left: %ds", secondsLeft];
secondsLeft--;
} else if (secondsLeft==0 && !_gameOver) {
// Invalidate timer
[timer invalidate];
[self timerExpire];
}
}
- (void)timerExpire
{
// Gameover
[self gameOver];
[_gameTimer invalidate];
_gameTimer = nil;
}

NSTimer needs to be a local variable so there can only be one instance of the object running through the loop. Here's the code.
- (void)countdownTimer
{
NSTimer *_gameTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(updateTime:) userInfo:nil repeats:YES];
NSRunLoop *gameRun = [NSRunLoop currentRunLoop];
[gameRun addTimer:_gameTimer forMode:NSDefaultRunLoopMode];
if (secondsLeft==0 || _gameOver) {
[_gameTimer invalidate];
_gameTimer = nil;
}
}
- (void)updateTime:(NSTimer *)timer
{
if (secondsLeft>0 && !_gameOver) {
_timerLabel.text = [NSString stringWithFormat:#"Time left: %ds", secondsLeft];
secondsLeft--;
} else if (secondsLeft==0 || _gameOver) {
// Invalidate timer
[timer invalidate];
[self timerExpire];
}
- (void)timerExpire
{
// Gameover
[self gameOver];
}

Related

how to resume time counter value in when i start the app

I want to resume time counter value in when I start the app.like first my label value is 05:00 than after close the app but when I start the app agin that time timer count start to 05:00. Please help me
int timeSec,timeMin ;
- (void)viewDidLoad {
timeSec=0;
timeMin=0;
[self StartTimer];
}
-(void) StartTimer
{
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(timerTick:) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
}
//Event called every time the NSTimer ticks.
- (void)timerTick:(NSTimer *)timer
{
timeSec++;
if (timeSec == 60)
{
timeSec = 0;
timeMin++;
}
//Format the string 00:00
NSString* timeNow = [NSString stringWithFormat:#"%02d:%02d", timeMin, timeSec];
//Display on your label
//[timeLabel setStringValue:timeNow];
self.lbl_timer.text= timeNow;
}
//Call this to stop the timer event(could use as a 'Pause' or 'Reset')
- (void) StopTimer
{
// [timer invalidate];
timeSec = 0;
timeMin = 0;
//Since we reset here, and timerTick won't update your label again, we need to refresh it again.
//Format the string in 00:00
NSString* timeNow = [NSString stringWithFormat:#"%02d:%02d", timeMin, timeSec];
//Display on your label
// [timeLabel setStringValue:timeNow];
self.lbl_timer.text= timeNow;
}
thanks for advance..
Try this code.store data in nsuserdefault
- (void)viewDidLoad {
timeSec=[[NSString stringWithFormat:#"%ld",(long)[[NSUserDefaults standardUserDefaults]integerForKey:#"timeSec"]] intValue];
timeMin=[[NSString stringWithFormat:#"%ld",(long)[[NSUserDefaults standardUserDefaults]integerForKey:#"timeMin"]] intValue];
[self StartTimer];
}
-(void) StartTimer
{
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(timerTick:) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
self.lbl_timer.text=#"00:00";
}
- (void)timerTick:(NSTimer *)timer
{
timeSec++;
if (timeSec == 60)
{
[locationManager startUpdatingLocation];
timeSec = 0;
timeMin++;
}
self.lbl_timer.text= [NSString stringWithFormat:#"%02d:%02d", timeMin, timeSec];;
}
when you back to the screen that time add this code.like back button or close button action
[timer invalidate];
[[NSUserDefaults standardUserDefaults]setInteger:timeSec forKey:#"timeSec"];
[[NSUserDefaults standardUserDefaults]setInteger:timeMin forKey:#"timeMin"];
Declare two variable in appdelegate file
1)NSUserDefaults *usedefaults;
2)#property (nonatomic,readwrite) int timeSec,timeMin,isBackground;
- (void)applicationDidEnterBackground:(UIApplication *)application
{
self.isBackground=1;
usedefaults=[NSUserDefaults standardUserDefaults];
[usedefaults setObject:[NSString stringWithFormat:#"%d",self.timeMin] forKey:#"timemin"];
[usedefaults setObject:[NSString stringWithFormat:#"%d",self.timeSec] forKey:#"timesec"];
NSLog(#"Enter in back value userdefault %#",usedefaults);
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
if(self.isBackground==1)
{
self.isBackground=0;
self.timeMin=[[usedefaults objectForKey:#"timemin"] intValue];
self.timeSec=[[usedefaults objectForKey:#"timesec"] intValue];
NSLog(#"Foreground value min %d sec %d",self.timeMin,self.timeSec);
}
}
In ViewDidload in your Timer startpage
app=(AppDelegate *)[[UIApplication sharedApplication] delegate];
finally just replace you self.timemin to app.timemin same for timesec.
Cheers enjoy That surely work for u ..

Can I use a NStimer in another NStimer?

I create a NSTimer:
timer = [NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:#selector(sendImage) userInfo:nil repeats:YES];
In the method sendImage, I create another NSTimer timer2. The code following:
- (void)sendImage
{
for(int i = 0;i < 50 ; i++)
{
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:socket forKey:#"socket"];//parameter which deliver to the method`sendPieceOfImage`
[dict setObject:pData forKey:#"pData"];
timer2 = [NSTimer scheduledTimerWithTimeInterval:0.002f target:self selector:#selector(sendPieceOfImage:) userInfo:dict repeats:NO];
}
}
But it didn't work. I want to know can NSTimer apply mechanically? If it's infeasible, what can I do in the sendImage. I hope every cycle in the for() can run with interval.
The answer to your question is YES. That's possible to schedule one timer in the firing callback of another. Consider this:
dispatch_async(dispatch_get_main_queue(), ^{
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(timer1Event:) userInfo:nil repeats:YES];
});
- (void)timer1Event:(NSTimer*)timer {
NSLog(#"timer1Event");
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(timer2Event:) userInfo:nil repeats:NO];
}
- (void)timer2Event:(NSTimer*)timer {
NSLog(#"timer2Event");
}
Even the problem is not fully described, I'll try to guess that the rootcause is in how very first timer is scheduled.
You need thread with aproprietaly setted up RunLoop. Main thread is suitable.
dispatch_async(dispatch_get_main_queue(), ^{
self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:#selector(sendImage) userInfo:nil repeats:YES];
});
If you don't want to load the main thread, consider this:
You need your own thread:
self.workerThread = [[NSThread alloc] initWithTarget:self selector:#selector(startRunLoop) object:nil];
[self.workerThread start];
Which starts the runloop:
- (void)startRunLoop
{
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
[runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
do {
#autoreleasepool
{
[runLoop runUntilDate:[NSDate dateWithTimeIntervalSinceNow:2.0]];
}
} while (![NSThread currentThread].isCancelled);
}
Now, for starting the timer on the worker thread you need this:
- (void)startTimer
{
self.timer = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:#selector(timerEvent:) userInfo:nil repeats:YES];
}
How to call:
[self performSelector:#selector(startTimer) onThread:self.workerThread withObject:nil waitUntilDone:NO];
Hope it helps.

Managing Timers Passed as Variables

I am trying to perform what I thought was a simple task. I have a handful of repeating timers that need to be started and stopped.
I created methods for starting and stopping the timers, and attempt to pass the timers to the methods as parameters.
The problem is that the timers never seem to be stopped. Any ideas why this might not be working properly? Thank you!
Top of File:
#import "ViewController.h"
NSTimer *launchTimer;
NSTimer *transactionTimer;
Starting Method:
-(void) startingMethod {
NSString *urlString = #"http://google.com";
[[AsynchRequestService sharedInstance]
performAsynchronousURLRequest:urlString completion:^(BOOL success,
NSString *responseBody, NSString *responseStatus) {
if (success) {
[self stopResponseTimer:launchTimer];
}
else {
[self startResponseTimer:launchTimer
method:#selector(startingMethod)
interval:10];
}
}];
}
Method to Start the Timer:
-(void)startResponseTimer:(NSTimer *) timer method:(SEL) method
interval:(int) interval {
[timer invalidate];
timer = nil;
timer = [NSTimer scheduledTimerWithTimeInterval:interval target:self
selector:method userInfo:nil repeats:YES];
}
Method to Stop the Timer:
-(void)stopResponseTimer:(NSTimer *) timer {
NSLog(#"STOP TIMER");
[timer invalidate];
timer = nil;
}
Make startResponseTimer and `stopResponseTimer' take the pointer to the object pointer intead.
-(void)startResponseTimer:(NSTimer **) timer method:(SEL) method
interval:(int) interval {
[*timer invalidate];
*timer = nil;
*timer = [NSTimer scheduledTimerWithTimeInterval:interval target:self
selector:method userInfo:nil repeats:YES];
}
-(void)stopResponseTimer:(NSTimer **) timer {
NSLog(#"STOP TIMER");
[*timer invalidate];
*timer = nil;
}
then invoke it like
[self startResponseTimer:&launchTimer];
[self stopResponseTimer:&launchTimer];
This should make sure that you retain the right NSTimer object.
NOTE:It is always a good idea to check a pointer to a pointer to an object for NULL in a public method

NSTimer does not stop when invalidate

I want to check if the application is idle (user doesn't take any action for the last 30 minutes) and log out the user.
For that I have an event manager that resets a timer.
- (void)sendEvent:(UIEvent *)event {
if(event == nil) {
[self resetIdleTimer];
} else {
[super sendEvent:event];
// Only want to reset the timer on a Began touch or an Ended touch, to reduce the number of timer resets.
NSSet *allTouches = [event allTouches];
if ([allTouches count] > 0) {
// allTouches count only ever seems to be 1, so anyObject works here.
UITouchPhase phase = ((UITouch *)[allTouches anyObject]).phase;
if (phase == UITouchPhaseBegan || phase == UITouchPhaseEnded)
[self resetIdleTimer];
}
}
}
- (void)resetIdleTimer {
if (self.idleTimer) {
[self.idleTimer invalidate];
self.idleTimer = nil;
}
NSInteger maxTime = 60*30; //30 minutes
self.idleTimer = [NSTimer scheduledTimerWithTimeInterval:maxTime target:self selector:#selector(checkIfIdleTimerExceeded) userInfo:nil repeats:NO];
}
- (void)checkIfIdleTimerExceeded {
theProfileManager = [[ProfileManager alloc] init];
theProfile = [theProfileManager getProfile];
if( ! [[theProfile getStatus]isEqualToString:#"u1"]) {
if( ! [[theProfile getTheUser] isUnlimitedLogin]) {
theProfile = nil;
theUserManager = [[UserManager alloc] init];
[theUserManager setCurrentUser:[theProfile getTheUser]];
[theUserManager setCurrentUserAccount:[[theProfile getTheUser] getTheUserAccount]];
[theUserManager setCurrentUserSettings:[[theProfile getTheUser] getTheUserSettings]];
[theUserManager logoutCurrentUser];
[[MenuItemDataManager alloc] deleteJsonData];
NSNotification *msg = [NSNotification notificationWithName:#"leftPanelMsg" object:[[NSString alloc] initWithFormat:#"Home"]];
[[NSNotificationCenter defaultCenter] postNotification:msg];
[self performSelector:#selector(loadHomeView:) withObject:nil afterDelay:0.5f];
}
}
[self resetIdleTimer];
}
The checkIfIdleTimerExceeded does the log out process.
Problem: After 15 minutes I touch the screen, the resetIdleTime is called and should restart a new NSTimer. But after 15 minutes the application logs the user out.
Thanks for your help.
André.
As per your requirement of the Touches event. You should do this:
NSSet *allTouchEvents = [event allTouches];
if ([allTouchEvents count] > 0) {
// allTouchEvents count only ever seems to be 1, so anyObject works here.
UITouchPhase phase = ((UITouch *)[allTouchEvents anyObject]).phase;
if (phase == UITouchPhaseBegan || phase == UITouchPhaseEnded)
[self resetIdleTimer];
}
And in the resetIdleTimer, The
self.idleTimer = [NSTimer scheduledTimerWithTimeInterval:maxTime target:self selector:#selector(checkIfIdleTimerExceeded) userInfo:nil repeats:NO];
should be like
self.idleTimer = [NSTimer scheduledTimerWithTimeInterval:maxTime target:self selector:#selector(checkIfIdleTimerExceeded:) userInfo:nil repeats:NO];
And checkIfIdleTimerExceeded should be like:
-(void) checkIfIdleTimerExceeded :(NSTimer*)timer
{
//Do your all process and invalidate after completion
[timer invalidate];
}
I'm not sure which one of your other methods can be called beside the –resetIdleTimer in your workflow when you touch the screen, but that solution works to me as you have described to like getting it worked:
I'm seeing in the log console the –resetTimer: will called if I tap a button within 7 secs, it resets the timer properly and creates a new 7 secs timer.
the logout method will call only if I don't touch my button on the screen in 7 secs time, and the timer finally invokes the –logout: method.
- (void)resetTimer:(NSTimer *)timer {
NSLog(#"reset time...");
if (timer.isValid) [timer invalidate], _timer = nil;
_timer = [NSTimer scheduledTimerWithTimeInterval:7.f target:self selector:#selector(logout:) userInfo:nil repeats:NO];
}
//
- (void)buttonTouchedUpInside:(UIButton *)sender {
NSLog(#"touched...");
[self resetTimer:_timer];
}
//
- (void)logout:(NSTimer *)timer {
NSLog(#"logout...");
if (timer.isValid) [timer invalidate], _timer = nil;
// logout ...
}

problems with new thread

After trying many ways to call a function in new thread only the below code worked for me
[NSThread detacNewThreadSelector:#selector(temp:) toTarget:self withObject:self];
The below didn't work:
NSThread *updateThread1 = [[NSThread alloc] initWithTarget:self selector:#selector(temp:) object:self];
NSThread *updateThread1 = [[NSThread alloc] init];
[self performSelector:#selector(temp:) onThread:updateThread1 withObject:self waitUntilDone:YES];
Now when i try to call NSTimer or perform selector in timer: function it does not works Find below the code
int timeOutflag1 = 0;
-(void)connectCheckTimeOut
{
NSLog(#"timeout");
timeOutflag1 = 1;
}
-(void)temp:(id)selfptr
{
//[selfptr connectCheckTimeOut];
NSLog(#"temp");
//[NSTimer scheduledTimerWithTimeInterval:5 target:selfptr selector:#selector(connectCheckTimeOut) userInfo:nil repeats:NO];
[selfptr performSelector:#selector(connectCheckTimeOut) withObject:nil afterDelay:5];
}
- (IBAction)onUart:(id)sender {
protocolDemo1 *prtDemo = [[protocolDemo1 alloc] init];
//NSThread *updateThread1 = [[NSThread alloc] initWithTarget:self selector:#selector(temp:) object:self];
//[self performSelector:#selector(temp:) onThread:updateThread1 withObject:self waitUntilDone:YES];
// [updateThread1 start];
[self performSelector:#selector(temp:) withObject:self afterDelay:0];
while(1)
{
NSLog(#"Whieloop");
if(timeOutflag1)
{
timeOutflag1 = 0;
break;
}
if([prtDemo isConnected])
break;
}
}
If i use [self performSelector:#selector(connectCheckTimeOut) withObject:nil afterDelay:5];
in onUart function then it works properly i can see Timeout printf but inside temp it does not work.
NSTimer is run-loop based, so if you want to use one on a background thread that you're spawning and managing yourself, you will need to start a runloop on that thread. Read up on NSRunLoop. The short version might look something like:
- (void)timedMethod
{
NSLog(#"Timer fired!");
}
- (void)threadMain
{
NSRunLoop* rl = [NSRunLoop currentRunLoop];
NSTimer* t = [NSTimer scheduledTimerWithTimeInterval: 1.0 target: self selector: #selector(timedMethod) userInfo:nil repeats:YES];
[rl run];
}
- (void)spawnThread
{
[NSThread detachNewThreadSelector: #selector(threadMain) toTarget:self withObject:nil];
}

Resources