1
self.timerProgress=[NSTimer scheduledTimerWithTimeInterval:50.0 target:self selector:@selector(stopProgressView) userInfo:nil repeats:NO];

-(void)stopProgressView
{
    if ([self.timerProgress isValid]) {
        [self.timerProgress invalidate];
        self.timerProgress=nil;
    }  

}

当我试图使 NSTimer 对象无效时单击按钮

-(void)cancelTimer
{
       if ([self.timerProgress isValid]) {
            [self.timerProgress invalidate];
            self.timerProgress=nil;
        }   
}

它不会无效。它在 50 间隔后调用一次 stopProgressView。如何解决这个问题?

4

4 回答 4

1
- (IBAction)stopTimer {
    if ([timerProgress isValid]) {
        [timerProgress invalidate];
    }
}

不要self.timerProgress使用仅使用timerProgress

于 2013-03-05T06:28:57.983 回答
1

最可能的原因是您的计时器安排在与您尝试使其无效的运行循环不同的运行循环上。

定时器必须在与调度它们的运行循环相同的线程/运行循环上失效。

Cocoa touch 不是线程安全的,因此您应该在主线程上运行所有与 UI 相关的活动。如果您在不同的线程上进行 GUI 工作,它可能会起作用,但是您会遇到随机崩溃,并且还会产生类似这样的计时器问题。

于 2014-07-11T09:45:42.533 回答
0

从您发布的内容看来,它应该可以工作。这就是我在我的应用程序中使用它的方式,它运行良好。

但是,您可以尝试制作一个带有计时器对象的选择器,例如:

-(void)stopProgressView:(NSTimer *)timer{
     //do stuff with timer here
}

请注意,这也意味着您应该将@selector(stopProgressView) 更改为@selector(stopProgressView:)。尽管为了记录,我当前的停止计时器功能只使用 [self.timer invalidate] 并且工作正常。

我对调试的另一条建议是使用 NSLogs 来确保每个方法实际上都被调用,并且当方法被调用时,if 子句中的 NSLog 以确保它有效。

于 2013-03-05T06:34:07.533 回答
0

你创建NSTimer没有NSRunLoop所以你NSTimer没有开始,在之后添加这个代码

self.timerProgress = [NSTimer scheduledTimerWithTimeInterval:50.0 
                                                      target:self 
                                                    selector:@selector(stopProgressView) 
                                                    userInfo:nil
                                                     repeats:NO];

 //add  

[[NSRunLoop currentRunLoop] addTimer:_tapTimer 
                             forMode:NSDefaultRunLoopMode];
于 2013-03-05T06:58:57.283 回答