[NSTimer scheduledTimerWithTimeInterval: target: selector: userInfo: repeats:NO陷阱

对于

NSTimer* refreshTimer_ = [NSTimer scheduledTimerWithTimeInterval:fSearchNewAlarmTimer target:self selector:@selector(requestNewMessage) userInfo:nilrepeats:YES];
[refreshTimer_fire];

 
 

我们常用的释放方式:

if (refreshTimer_ !=nil) {
        [refreshTimer_invalidate];
        refreshTimer_ =nil;
}


如果repeats:NO,上面的释放方式会crash,原因是违背谁retain谁释放的原则,


解决方法:

方法1:直接refreshTime_ = nil;

方法2:判断是否健在,再释放

1)创建定时器

BOOL bRunTimerFuncFlag =NO; // timer函数执行标志
NSTimer* refreshTimer_ = [NSTimer scheduledTimerWithTimeInterval:fSearchNewAlarmTimer target:self selector:@selector(requestNewMessage) userInfo:nil repeats:YES];
[refreshTimer_ fire];

2)定时器函数

-(void)requestNewMessage
{
    bRunTimerFuncFlag =YES;
}

3)释放

if (! bRunTimerFuncFlag) {
        [refreshTimer_ invalidate];
        refreshTimer_ =nil;
 }


参考文章:

http://stackoverflow.com/questions/5191272/iphone-do-i-need-to-invalidate-timer-when-repeats-no

http://stackoverflow.com/questions/6038698/nstimer-to-retain-or-not-to-retain

你可能感兴趣的:(NSTimer,No,repeats)