小伙伴在開發過程中,一定遇到過這樣的需求,需要定時請求某個接口,獲取數據,為了界面的流暢和代碼的簡潔,就會用上多線程。
那一定遇到過這樣的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);
}