NSTimer在一个序列中有多个时间间隔

在不创build多个NSTimer实例的情况下,如何实现一个NSTimer来以一个序列中的不同间隔触发特定或多个方法。 例如method1(0.3秒),method2(0.5),method3(0.7)等等。

如果有人可以请分享任何示例代码,我将不胜感激。

我不确定你的最终目标是什么,但是在阅读完你的问题之后, 我build议你尝试下面的方法 ,也许这就是你要找的。

你应该把这个代码放在你通常想用不同的时间间隔启动同一个NSTimer类的地方(不幸的是,这是不可能的)。

 { // ... [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]; // ... } 

当需要排除所有排队的select器时,使用这个代码。

 [NSObject cancelPreviousPerformRequestsWithTarget:self]; 

NSTimer本身不提供这种function,它会以固定的时间间隔一次或重复触发。 您将需要多个定时器来达到这个效果,或者完全离开NSTimer

我相信你应该通过当前的时间间隔发射select器,并在那里进一步处理。 如果时间间隔为0.3,则可以调用method1,0.5 – method2,这很可能没有其他办法来实现

制作一个包装来包装NSTimer方法调用,如下所示:

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

你可以调用这个方法,按照你的要求传递时间间隔和select器方法。

在select器方法中使用timeinterval = 0.1的select器创build一个计时器,你可以通过保持一个静态的floatvariables来检查,并且每次加0.1,如:

 static CGFloat counter= 0; counter+= 0.1; 

然后检查计数器的值,并调用你的方法..

 if(0.3 == counter) { [self callMethod1]; } else if(0.5 == counter) { [self callMethod2]; } else if(0.7 == counter) { [self callMethod3]; } ... ... .. ..