How can I update my NSTimer as I change the value of the time interval

只谈情不闲聊 提交于 2019-12-22 05:08:07

问题


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.


回答1:


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];



回答2:


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.



来源:https://stackoverflow.com/questions/3989179/how-can-i-update-my-nstimer-as-i-change-the-value-of-the-time-interval

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