How can I update my NSTimer as I change the value

2019-04-25 01:50发布

I have an NSTtimer implemented and it's working fine. I also have the time interval argument connected to a UISlider for the iPhone. However when I change it's value the NSTimer is still running at the original time interval it does not get updated. How can I implement an NSTimer and have it change it's time interval as the value of my UISlider changes. Below is the line I am using for the NSTimer.

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

I want it to constantly update it time interval with the value of the UISlider.

2条回答
地球回转人心会变
2楼-- · 2019-04-25 02:34

You can do something like this using 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];
                   }

               });

And change the value of timeInterval from else where in the code.

查看更多
Ridiculous、
3楼-- · 2019-04-25 02:35

You can't I'm afraid. Invalidate it with:

[myTimer invalidate];

Then create a new one with the new time. You may have to set it to nil first as well.

myTimer = nil;
myTimer = [NSTimer scheduledTimerWithTimeInterval:mySlider.value 
                                           target:self 
                                         selector:@selector(myMethod) 
                                         userInfo:nil 
                                          repeats:YES];
查看更多
登录 后发表回答