NSTimer with multiple time intervals in a sequence

2019-05-02 09:46发布

Without creating multiple NSTimer instances, how would one achieve an NSTimer to fire a specific or multiple method with different intervals in a sequence. For example method1 (0.3 sec), method2 (0.5), method3 (0.7) and so on.

I would appreciate if someone could please share any example code.

5条回答
男人必须洒脱
2楼-- · 2019-05-02 09:55

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.

查看更多
Ridiculous、
3楼-- · 2019-05-02 09:59

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];
}
...
...
..
..
查看更多
闹够了就滚
4楼-- · 2019-05-02 10:06

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];
查看更多
老娘就宠你
5楼-- · 2019-05-02 10:10

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

查看更多
叛逆
6楼-- · 2019-05-02 10:19

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.

查看更多
登录 后发表回答