NSTimer with multiple time intervals in a sequence

时光怂恿深爱的人放手 提交于 2019-12-05 10:55:53
holex

I'm not sure what your final goal is with this but after reading your question I would recommend to try the following way, maybe this is what you'd look for.

you should put this code where you normally wanted to start the same NSTimer class with different intervals (what is not possible, unfortunately).

{
    // ...
    [self performSelector:@selector(method1) withObject:nil afterDelay:0.3f];
    [self performSelector:@selector(method2) withObject:nil afterDelay:0.5f];
    [self performSelector:@selector(method3) withObject:nil afterDelay:0.7f];
    // ...
}

and when need to unschedule all those selectors queued, use this code.

[NSObject cancelPreviousPerformRequestsWithTarget:self];

NSTimer itself does not provide that functionality, it fires either once or repeatedly at fixed intervals. You will require multiple timers to achieve this effect, or move away from NSTimer entirely.

i beleive you should pass current time interval to the fired selector and further handle it there. if time interval is 0.3 you call method1, 0.5 - method2, there's most likely no other way to implement this

Make a wrapper to wrap the NSTimer method call like this:

- (void) CallTimerWithTimeInterval:(float) interval andSelector:(NSString *)methodName 
{
SEL selector = selectorFromString(methodName);
    [NSTimer scheduledTimerWithTimeInterval:interval target:self selector:@selector(selector) userInfo:nil repeats:YES];
}

You can call this method and pass the interval and selector method as per your requirement.

create an timer with selector with timeinterval = 0.1 from there in the selector method, you can check by keeping a static float variable and add 0.1 to it everytime like:

static CGFloat counter= 0;

counter+= 0.1;

then check the counter value and call ur methods..

if(0.3 == counter)
{
    [self callMethod1];
}
else if(0.5 == counter)
{
    [self callMethod2];
}
else if(0.7 == counter)
{
    [self callMethod3];
}
...
...
..
..
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!