I am using an NSTimer in my view class that is called every 15 seconds. My problem is, it is working properly, but my app is getting slow, because it is showing its performance to the whole app. So I want to pause the NSTimer when my view disappears from its superview and restart the timer when it appears. Please help me in solving the problem. Here is my code:
- (void) viewWillAppear:(BOOL)animated
{
if(!Thread_bool)
{
//[spinner startAnimating];
NSTimer *timer_new1=[[NSTimer alloc] init];
timer_new1=[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(threadMethod) userInfo:nil repeats:YES];
self.timer_new=timer_new1;
[timer_new1 release];
[self.tableView setEditing:NO];
isEditing=NO;
Thread_bool=YES;
}
}
-(void)viewWillDisappear:(BOOL)animated
{
[self.timer_new invalidate];
timer_new=nil;
}
In first line you have alloced a timer and in second line another timer is created and assigned to
timer_new1. So you lost the reference to the timer that was alloced in previous line and that is leaked. You don’t need the first line alloc. Do this:And remove
[timer_new1 release];(I am assuming thatself.timer_newis retained). Also inviewWillDisappeardoself.timer_new = nil;instead oftimer_new=nil;. Adding thatselfwill call the setter and correctly release the previous timer.