I want to start a timer when a viewWillAppear method gets called.
It's working perfectly, but I'm having a problem when I push a new view on this Current View, which already has a timer. When I pop that new View and recall viewWillAppear I want to start the timer again as before. I have most of the techniques but can't find a solution.
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[NSThread detachNewThreadSelector:#selector(createTimer) toTarget:self withObject:self];
}
- (void)createTimer
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
gameTimer = [[NSTimer timerWithTimeInterval:1.00 target:self selector:#selector(timerFired:) userInfo:nil repeats:YES] retain];
[[NSRunLoop currentRunLoop] addTimer:gameTimer forMode:NSDefaultRunLoopMode];
timeCount = 360;
[runLoop run];
[pool release];
}
- (void)timerFired:(NSTimer *)timer
{
if(timeCount == 0)
{
[self timerExpired];
} else {
timeCount--;
if(timeCount == 0) {
[timer invalidate];
[self timerExpired];
}
}
timeLabel.text = [NSString stringWithFormat:#"%02d:%02d",timeCount/60, timeCount % 60];
}
- (void) timerExpired
{
//NSLog(#"Final == %#",arrayAnswers);
//NSLog(#"Attempt == %d",[arrayAnswers count]);
[gameTimer invalidate];
gameTimer = nil;
}
Well, based on experience, your problem is the timer's thread. Basically, the problem is here:
[NSThread detachNewThreadSelector:#selector(createTimer) toTarget:self withObject:self];
I'm not absolutely sure but I believe that your code is not really wrong. I haven't figured it out yet but I guess the NSTimer object is not being activated when detachNewThreadSelector: is used. Try executing the timer on the main thread.
[self performSelectorOnMainThread:#selector(createTimer) withObject:nil waitUntilDone:NO]
I've done this and got the results that I wanted.
Related
Hi i want to start a timer with another thread and want to repeat process in that thread. i had tried but it doesn't work.
my code snippet is given below
[NSThread detachNewThreadSelector:#selector(setupTimerThread) toTarget:self withObject:nil];
-(void)setupTimerThread
{
NSLog(#"inside setup timer thread");
// self.startTiemr = [[NSTimer alloc]init];
startTiemr = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:#selector(triggerTimer) userInfo:nil repeats:YES];
runLoop = [NSRunLoop currentRunLoop];
[runLoop addTimer:startTiemr forMode:NSRunLoopCommonModes];
[runLoop run];
}
can anyone suggest me a proper way to do that?
Thanks in advance.
#import "TimePassViewController.h"
#interface TimePassViewController ()
#end
#implementation TimePassViewController
{
NSTimer *timer;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// [self performSelectorOnMainThread:#selector(yourmethod) withObject:nil waitUntilDone:NO];
NSThread* myThread = [[NSThread alloc] initWithTarget:self
selector:#selector(yourmethod)
object:nil];
[myThread start]; // Actually create the thread
}
-(void)yourmethod
{
#autoreleasepool
{
NSRunLoop *TimerRunLoop = [NSRunLoop currentRunLoop];
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(timerMethod) userInfo:nil repeats:YES];
[TimerRunLoop run];
}
//timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(timerMethod) userInfo:nil repeats:YES];
}
-(void)timerMethod
{
NSLog(#"aaaaaaaaaaaa");
//[timer invalidate];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
try this code:
NStimer *uptimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(bachground_todaylist) userInfo:nil repeats:YES];
-(void)bachground_todaylist
{
[self performSelectorInBackground:#selector(yourmethod) withObject:nil];
}
you wants to stop proces
[uptimer invalidate];
I have start a timer to call a method after 10 seconds. the timer start from didFinishLaunchingWithOptions. it works fine but I want to stop that timer from another UISubclass at the time of logout. How I can do this my code is
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[NSThread sleepForTimeInterval:2.0];
[self.window addSubview:viewController.view];
[self setupTimer];
[self.window makeKeyAndVisible];
return YES;
}
-(void)setupTimer;
{
timer = [NSTimer timerWithTimeInterval:10
target:self
selector:#selector(triggerTimer:)
userInfo:nil
repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}
-(void)triggerTimer:(NSTimer*)timer;
{
NSLog(#"===============this method is call after every 10 second===========================");
Getlocation *object=[[Getlocation alloc] init];
[object updatelocation];
}
-(void)stopTimer:(NSTimer*)timer;
{
[timer invalidate];
timer=nil;
}
if([timer isValid])
[timer invalidate];
timer = nil;
Take an object of NSTimer.
Write this line where do you want to call method
timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:#selector(NEWTIMER) userInfo:nil repeats:YES];
Write this code there do you want stop timer.
[timer invalidate];
timer = nil;
[timer release];
if you want stop timer when your app came background .you should write this code into this method.
- (void)applicationWillEnterForeground:(UIApplication *)application
{
[timer invalidate];
timer = nil;
[timer release];
}
Write code in logout ButtonAction method.
-(IBAction)LogOutButtonPressed:(id)sender {
[timer invalidate]; timer = nil; [timer release];
}
I am having issue with invalidating a NSTimer.
I initialize a NSTimer with below function.
-(void) initLTTimer{
[self shutLTTimer];
[self setQuestion:questionCounter];
isQuestionAttempt=NO;
tmLeftTime=[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:#selector(updateLeftTime:) userInfo:nil repeats:YES];
NSLog(#"Timer Initialized");
}
further I called a function updateLeftTime in its selector.
- (void)updateLeftTime:(NSTimer *)theTimer {
NSLog(#"%d",timeCounter);
timeCounter+=1;
tfLeftTime.text=[NSString stringWithFormat:#"%d", (QUESTION_TIME_LIMIT-timeCounter)];
if (timeCounter>=QUESTION_TIME_LIMIT) {
if (isQuestionAttempt==NO) {
[self increaseDropShots];
}
[self setQuestionBg];
timeCounter=0;
[self shutLTTimer];
[self updateQuestion:nil];
}
}
This function [self increaseDropShots]; called in above function.
here is the code of this function
-(void)increaseDropShots
{
NSString *imgName = #"DactiveRetake";
if (IS_IPAD) {
imgName = [imgName stringByAppendingString:#"_ipad"];
}
wrongAttemp+=1;
for (int i =1; i<=wrongAttemp; i++ )
{
UIImageView *img=(UIImageView *)[self.view viewWithTag:i+50];
[img setImage:[UIImage imageNamed:imgName]];
}
NSLog(#"Question dropped counter: %d",wrongAttemp);
if (wrongAttemp == 3)
{
[self shutLTTimer];
[CommonFunctions initGlobalVars];
[Bgplayer stop];
[Bgplayer release];
OverPageViewController *opvc=[[OverPageViewController alloc] initWithNibName:[CommonFunctions getXIBFile:#"OverPageViewController"] bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:opvc animated:YES];
[opvc release];
}
}
In this function I am killing this timer but I am unable.
-(void) shutLTTimer{
if ([tmLeftTime isValid]) {
[tmLeftTime invalidate];
tmLeftTime=nil;
}
}
This is the whole scenario of my application
Please help me what is the issue.
Answered after conversation in comments
Does the code definitely get to the line, [tmLeftTime invalidate];? You can check this by using a breakpoint or an NSLog.
i added [self fbButtonClick:nil]; , but it does't call login screen. Why?
- (void)viewDidLoad {
_facebook = [[Facebook alloc] initWithAppId:kAppId];
[self.label setText:#"Please log in"];
_getUserInfoButton.hidden = YES;
_getPublicInfoButton.hidden = YES;
_publishButton.hidden = YES;
_uploadPhotoButton.hidden = YES;
_fbButton.isLoggedIn = NO;
[_fbButton updateImage];
[self fbButtonClick:nil];
}
You're suppose to call the authorize method on the _facebook object to login. That will call the login screen
i solved this problem with timer
NSTimer *timer = [[NSTimer timerWithTimeInterval:0.001
target:self
selector:#selector(timerFired:)
userInfo:nil
repeats:NO] retain];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
- (void)timerFired:(NSTimer *)timer
{
[timer invalidate];
[timer release];
timer = nil;
[self fbButtonClick:nil];
}
I am trying to run a NSTimer on a thread using iPhone SDK 3.0. I think I am doing everything correctly (new runloop etc.). If I call [timer invalidate] on viewDidDissappear though I get this error:
bool _WebTryThreadLock(bool), 0x3986d60: Tried to obtain the web lock from a thread other than the main thread or the web thread. This may be a result of calling to UIKit from a secondary thread. Crashing now...
Program received signal: “EXC_BAD_ACCESS”.
Here is my code:
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[activityIndicator startAnimating];
NSThread* timerThread = [[NSThread alloc] initWithTarget:self selector:#selector(timerStart) object:nil]; //Create a new thread
[timerThread start]; //start the thread
}
-(void)timerStart
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
//Fire timer every second to updated countdown and date/time
timer = [[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(method) userInfo:nil repeats:YES] retain];
[runLoop run];
[pool release];
}
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
[timer invalidate];
}
When I remove the line invalidating the timer everything works fine. Am I not supposed to invalidate it or am I making some other mistake?
Thanks
Try
[timer performSelector:#selector(invalidate) onThread:timerThread withObject:nil waitUntilDone:NO];
instead. You will have to make timerThread an ivar of your view controller.
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
NSThread* timerThread = [[NSThread alloc] initWithTarget:self selector:#selector(timerStart) userInfo:nil repeats:TRUE];
[timerThread start];
}
-(void)timerStart
{
#autoreleasePool{
NSRunLoop *TimerRunLoop = [NSRunLoop currentRunLoop];
[NSTimer scheduleTimerWithInterval:0.1 target:self selector:#selector(methodName:) userInfo:nil repeat:YES];
[TimerRunLoop run];
}
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
}
I guess you have done some UI work in "method".
timer = [[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(method) userInfo:nil repeats:YES] retain];
From the log, it seems you have done UI updating work it in "Timer" thread in "method".
you can use block to dispatch work on main thread or performSeletorOnMainThread for doing "method"