Reputation: 4594
I have done the following:
header file
NSTimer *timer1;
NSTimer *timer2;
implementation file
- (void)viewDidLoad
{
if(!timer1)
timer1 = [NSTimer scheduledTimerWithTimeInterval:30.0 target: self selector: @selector(repeatRequest) userInfo: nil repeats: YES];
if(!timer2)
timer2 = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
// Release any retained subviews of the main view.
[timer1 invalidate];
[timer2 invalidate];
}
So when I leave the current view these two lines make my app crash:
[timer1 invalidate];
[timer2 invalidate];
Anyone any idea why?Or does someone know any other method to stop the timer when I leave the current view?Thank you
EDIT: timer2 calls this method:
- (void) repeatRequest{
NSLog(@"backgroundRequest");
[NSThread detachNewThreadSelector:@selector(backgroundRequest) toTarget:self withObject:nil];
}
which does a ASIHTTPRequest
at server side.
now I kept only:
[timer1 invalidate];
and it doesn't block anymore...but what I do with timer2?
Upvotes: 0
Views: 173
Reputation: 738
these 2 lines actually should not be bad - in case you dealloc the viewcontroller and therefore the view disappears.
if you can switch back to your view, viewDidLoad is NOT beeing called. in that case, timer1 and timer2 are, as logancautrell said, dangling.
so what you want to try is:
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[timer1 invalidate];
timer1 = nil;
[timer2 invalidate];
timer2 = nil;
}
as well as moving
if(!timer1)
timer1 = [NSTimer scheduledTimerWithTimeInterval:30.0 target: self selector: @selector(repeatRequest) userInfo: nil repeats: YES];
if(!timer2)
timer2 = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
to your
-(void)viewDidAppear:(BOOL)animated
then it should not trouble you.
Upvotes: 3
Reputation: 8772
You have to set the timer ivars to nil whenever you invalidate. Otherwise you have a dangling pointer.
Upvotes: 1