通常在使用NSTimer時(shí)是如下:
這樣self強(qiáng)引用timer帜矾,timer強(qiáng)引用self,會造成self和timer循環(huán)引用,self和timer都銷毀不了。
//需要主動開啟timer
NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self
selector:@selector(loopTimer:) userInfo:nil repeats:YES];
self.timer = timer;
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
[runLoop addTimer:timer forMode:NSRunLoopCommonModes];
[runLoop run];
//自動開啟timer
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self
selector:@selector(loopTimer:) userInfo:nil repeats:YES];
self.timer = timer;
//定時(shí)器回調(diào)
- (void)loopTimer:(NSTimer *)timer{
//執(zhí)行任務(wù)
}
解決方案:使用isLoop變量記錄狀態(tài),在需要銷毀定時(shí)器的時(shí)候把isLoop賦值為NO。
//需要主動開啟timer
NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self
selector:@selector(loopTimer:) userInfo:nil repeats:YES];
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
[runLoop addTimer:timer forMode:NSRunLoopCommonModes];
[runLoop run];
self.isLoop = YES;
//自動開啟timer
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self
selector:@selector(loopTimer:) userInfo:nil repeats:YES];
self.isLoop = YES;
//定時(shí)器回調(diào)
- (void)loopTimer:(NSTimer *)timer{
if(self.isLoop = YES){
//執(zhí)行任務(wù)
}else{
//停止timer 并銷毀
[timer invalidate];
timer = nil;
}
}