2010-10-21 93 views
7

我有一个NSTtimer实施,它工作正常。对于iPhone,我也有连接到UISlider的时间间隔参数。但是,当我更改它的值时,NSTimer仍以原始时间间隔运行,但不会更新。我如何实现NSTimer,并随着我的UISlider的值更改而改变它的时间间隔。以下是我用于NSTimer的行。我如何更新我的NSTimer,因为我改变了时间间隔的值

[NSTimer scheduledTimerWithTimeInterval:mySlider.value 
           target:self 
           selector:@selector(myMethod) 
           userInfo:nil 
           repeats:YES]; 

我希望它不断更新它的时间间隔与UISlider的值。

回答

6

你不能害怕。使之无效:

[myTimer invalidate]; 

然后用新时间创建一个新的。您可能必须先将其设置为零。

myTimer = nil; 
myTimer = [NSTimer scheduledTimerWithTimeInterval:mySlider.value 
              target:self 
             selector:@selector(myMethod) 
             userInfo:nil 
              repeats:YES]; 
+0

你认为这是如果我想要实现闪光灯模式来打开和关闭iPhone 4的方式去走灯光LED – cgossain 2010-10-21 15:43:55

+0

如果你想要一个可变的计时器,它是。想想两个定时器可能会相互抵消,尽管这可能对您的应用程序无效。 – Ben 2010-10-21 15:47:27

+0

非常感谢您的帮助,我会看看如果我能得到它的工作。 – cgossain 2010-10-21 15:54:21

0

可以使用GCD

NSTimeInterval timeInterval=1; 
BOOL timerInvalidate=NO; 
dispatch_async(dispatch_get_global_queue(0, 0), 
       ^{ 
        while (!timerInvalidate){ 
        dispatch_async(dispatch_get_global_queue(0, 0), 
        ^{ 
        //your code; 
        }); 
        [NSThread sleepForTimeInterval:timeInterval]; 
        } 

       }); 

做这样的事情而来自其他地方的代码更改一个时间间隔的值。

相关问题