简体   繁体   中英

How to pause and restart an NSTimer when view disappears?

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;  
}
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];

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:

NSTimer *timer_new1 = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(threadMethod) userInfo:nil repeats:YES];

And remove [timer_new1 release]; (I am assuming that self.timer_new is retained). Also in viewWillDisappear do self.timer_new = nil; instead of timer_new=nil; . Adding that self will call the setter and correctly release the previous timer.

You have two lines there which are creating an instance of NSTimer . The first is

    NSTimer *timer_new1 = [[NSTimer alloc] init];

and the second is

    timer_new1 = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(threadMethod) userInfo:nil repeats:YES];

The NSTimer object created by the first line is retained, which you seem to be aware of because you're trying to release it later. However, the second line above is creating a new instance of NSTimer, which is autoreleased . When you do this, the first non-released NSTimer object is being leaked!

If you've set up your accessor method for timer_new to retain the timer, then delete the first line from above and don't release timer_new1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM