开发者

NSTimer fire problem(not the common invalidate issue)

my code as below:

- ( void ) restart {
    [ self pause ];
    //init something here...
    [ self proceed ];
}

- ( void ) pause {
    if ( [ _timer isValid ] ) {
        [ _timer invalidate ];
        _timer = nil;
    }
}

- ( void ) proceed {
    _timer = [ NSTimer scheduledTimerWithTimeInterval: 0.1 target: self selector: @selector ( fireHandler ) userInfo: nil repeats: YES ];
}

Mostly it works fine, but I found that in some case, after I invoked the method "restart" more than one time, sometimes, the fireHandler had been invoked more than one time within a single timeInterval(or the timeInterval was become shorter, anyway, it runs faster suddenly).

Now I add the sender to the fireHandler, and use NSLog to check the memory address, I found something as below:

<_NSCFTimer: 0x4e610a0> <_NSCFTimer: 0x4e610a0> <_NSCFTimer: 0x4e610a0> <_NSCFTimer: 0x4e610a0> <_NSCFTimer: 0x4e610a0> <_NSCFTimer: 0x4e610a0>

and repeat... It means that it is always the same timer. But sometimes when I call "restart" again, it indicates

<_NSCFTimer: 0x4e3d740> <_NSCFTimer: 0x4e610a0> <_NSCFTimer: 0x4e3d740> <_NSCFTimer: 0x4e610a0> <_NSCFTimer: 0x4e3d740> <_NSCFTimer: 0x4e610a0>...repeats

It means there are two timer, it seems that the first one has not been invalidate and release on time. It runs with the second one at 开发者_如何学编程the same time, and some seconds later, after the second one has be removed, even that the first one still alive!

It will appear again after a while. Such situation is not very often, without rules, it happens about 30% of the whole time. I have not any idea about this....Please if anyone can give me some idea to get the exactly problem, at least.


[NSTimer scheduledTimerWithTimeInterval] creates and schedules a new timer each time you call it. So when you call proceed several times, the system creates and starts a new timer each time, overriding your _timer reference and creating leaks.

I can't say why you get the behavior to describe, but accidentally calling proceed several times could be the cause. Consider rewriting it like this instead and see if that helps:

- (void)proceed 
{
    [_timer invalidate];
    _timer = [NSTimer schedule...];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜