代码之家  ›  专栏  ›  技术社区  ›  Sergey92zp

NSTimer不会因失效而停止

  •  6
  • Sergey92zp  · 技术社区  · 11 年前

    我这样添加计时器

    tim=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(repeatTim) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:tim forMode:NSDefaultRunLoopMode];
    

    提姆 它是我类的NSTimer属性。

    然后我按一下按钮就停止了

    [[fbt tim] invalidate];
    [fbt setTim:nil];
    

    fbt这是我班的一个例子。

    如果我只调用invalide,那么它不会停止,但如果我将其设置为nil,那么我得到EXC_BREAKPOINT

    这里是选择器中repeatTim方法的代码

    AppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
    [appDelegate.wbv stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"intal()"]];
    

    我试着打电话 初始化 使无效 在里面

    dispatch_async(dispatch_get_main_queue(), ^{})
    

    它也不会停止计时器。

    3 回复  |  直到 11 年前
        1
  •  5
  •   Tunaki    8 年前

    您有多个计时器在运行。试试这个:

    -(void)startTimer{
        [self.myTimer invalidate]; // kill old timer
        self.myTimer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(doSomething) userInfo:nil repeats:YES];
    }
    
    -(void)stopTimer{
        [self.myTimer invalidate];  
        self.myTimer=nil; //set pointer to nil 
    }
    
        2
  •  4
  •   Community CDub    4 年前

    阅读NSTimer的文档:

    有三种方法可以创建计时器:

    1. 使用scheduledTimerWithTimeInterval:invocation:repeats:或scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:class方法来创建计时器,并在默认模式下在当前运行循环中对其进行调度。

    2. 使用timerWithTimeInterval:invocation:repeats:或timerWithTimeInterval:target:selector:userInfo:repeats:class方法创建计时器对象,而不将其安排在运行循环中。(创建计时器后,必须通过调用相应NSRunLoop对象的addTimer:forMode:方法,手动将计时器添加到运行循环中。)

    3. 分配计时器并使用initWithFireDate:interval:target:selector:userInfo:repeats:method对其进行初始化。(创建计时器后,必须通过调用相应NSRunLoop对象的addTimer:forMode:方法,手动将计时器添加到运行循环中。)

    您使用的方法已将其从1添加到mainLoop。-你需要删除这一行,或者用2创建一个计时器。接近并离开手动添加。

    还要记住,您必须从安装计时器的线程发送无效消息。如果您从另一个线程发送此消息,则与计时器关联的输入源可能不会从其运行循环中删除,这可能会阻止线程正确退出。

        3
  •  0
  •   Priyanka    4 年前

    我已经尝试了所有可能的解决方案,但无法解决这个问题。最后,我在初始化计时器时设置了重复“false”,如下所示

    self.timer=timer.scheduledTimer(时间间隔:1,目标:self,选择器:#选择器(viewcontroller.methodname),userInfo:nil,重复次数:false)

    并且需要在我的选择器方法中添加上面的一行,用于我想要重复时间的任何条件。

    例如:-我的要求是我想反复调用一些方法,直到满足一个条件。因此,我没有添加重复true,而是将其设置为false,因为在我的情况下,重复true不会使计时器无效。

    我在我的viewdidload方法中添加了以下内容

    self.timer=timer.scheduledTimer(时间间隔:1,目标:self,选择器:#选择器(viewcontroller.method),userInfo:nil,重复次数:false)

    在选择器功能中,我添加了以下代码:-

    func method{
       if condition matched{
            // here your timer will be invalidated automatically
       }
       else{
           self.timer = Timer.scheduledTimer(timeInterval: 1, target: self,selector: #selector(viewcontroller.method), userInfo: nil,repeats: false)
       }
    }
    

    希望这能解决你的问题。

    快乐编码:)