search

Home  >  Q&A  >  body text

objective-c - I started a runloop in a thread and started a timer, but I found that dealloc was not used when the page returned and the timer could not be stopped. Please help me.

#import "MyViewController.h"

@interface MyViewController ()
{
    NSTimer *_timer;
}
@end

@implementation MyViewController

- (void)dealloc
{
    [_timer invalidate];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(changeCountdownTime) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
}

- (void)changeCountdownTime
{
    // do something
}

- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}
淡淡烟草味淡淡烟草味2801 days ago651

reply all(1)I'll reply

  • PHP中文网

    PHP中文网2017-05-02 09:37:06

    The recommended way to write is to first write [_timer invalidate]; and then write _timer = nil; in viewWillAppear: before destroying the vc and calling the -dealloc method.

    reply
    0
  • Cancelreply