美文网首页OC开发资料收集区
多线程定时器(循环请求)

多线程定时器(循环请求)

作者: 蜗牛锅 | 来源:发表于2017-07-28 15:00 被阅读18次

小伙伴在开发过程中,一定遇到过这样的需求,需要定时请求某个接口,获取数据,为了界面的流畅和代码的简洁,就会用上多线程。
那一定遇到过这样的bug,push到下一个界面了,定时器还是没有停止,dealloc的方法没有走,pod到上一界面,走了dealloc,定时器不会停止,而且说不定什么时候 程序就闪退了。
于是我在viewWillDisappear的方法里也进行定时器的释放,这样好了。不多说了,上代码吧。


// Block弱引用
#define WS(weakSelf)  __weak __typeof(&*self)weakSelf = self;
@interface DemoController 

{
// 
    dispatch_source_t _dataTimer;//定时器
}
@end


-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (_dataTimer) {
        dispatch_cancel(_dataTimer);
        _dataTimer = nil;
    }
}
-(void)dealloc
{
    if (_dataTimer) {
        dispatch_cancel(_dataTimer);
        _dataTimer = nil;
    }
}

-(void)createTimer{
 
    WS(weakSelf)
    
    NSTimeInterval period = 5.0; //设置时间间隔
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _dataTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_dataTimer, dispatch_walltime(NULL, 0), period * NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_dataTimer, ^{
        //在这里执行事件
        NSLog(@"每秒执行test");
  
    });
    
    dispatch_resume(_dataTimer);
    
}

相关文章

网友评论

    本文标题:多线程定时器(循环请求)

    本文链接:https://www.haomeiwen.com/subject/gftflxtx.html