Using NSTimer in a Loop

拥有回忆 提交于 2019-12-02 07:54:24

You can use the scheduledTimerWithTimeInterval

[NSTimer scheduledTimerWithTimeInterval: 0.5
             target: self
             selector: @selector(handleTimer:)
             userInfo: nil
             repeats: NO];

And inside the handleTimer you create the next timer

Looks like you are calling some method called 'timer' on self. What does it do? Creates a new timer? Then this is why. When a timer is created, it doesn't block. Instead a method call is scheduled and executed once the timer timeout passes.

What you could do is the following:

  • Create a class that holds an NSTimer
  • This class would have a variable to hold how many times it needs to count
  • At the end of one timer (and really, the only one) firing, it decrements the count

You can have the NSTimer repeat by calling it with:

[NSTimer scheduledTimerWithTimeInterval:30.0f
                             target:self 
                           selector:@selector(timerFired)
                           userInfo:nil
                            repeats:YES];

In a method called - (void)timerFired, you would decrement the count. If it reaches zero, you would stop the timer.

Hope this helps!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!