我怎样才能用这个简单的while循环使用NSTimer?
我有一个 – (void)方法正在执行,并在一个点上得到一个while循环,直接从加速度计获取值的那一刻
我在整个关于NSTimer类的文档中进行了讨论,但我无法理解我在这种情况下如何使用这个对象:
例如
-(void) play { ...... ... if(accelerationOnYaxis >0 && accelerationOnYaxis < 0.9 ) { startTimer; } while(accelerationOnYaxis >0 && accelerationOnYaxis < 0.9) { if(checkTimer >= 300msec) { printOut_AccelerationStayedBetweenThoseTwoValuesForAtLeast300msecs; break_Out_Of_This_Loop; } } stopTimerAndReSetTimerToZero; ..... more code... .... ... }
任何帮助?
你不能用NSTimer
来做,因为它需要你的代码退出才能触发。 NSTimer
使用事件循环来决定何时回叫; 如果你的程序在while
循环中保存了控件,那么定时器就没有办法触发,因为检查是否需要触发的代码永远不会被触发。
最重要的是,在这个忙碌的环境中待上将近一秒半的时间将会耗尽你的电池。 如果您只需要等待sleepForTimeInterval:
,则最好调用sleepForTimeInterval:
如下所示:
[NSThread sleepForTimeInterval:1.4];
您也可以使用<time.h>
clock()
来测量短时间间隔,如下所示:
clock_t start = clock(); clock_t end = start + (3*CLOCKS_PER_SEC)/10; // 300 ms == 3/10 s while(accelerationOnYaxis >0 && accelerationOnYaxis < 0.9) { if(clock() >= end) { printOut_AccelerationStayedBetweenThoseTwoValuesForAtLeast300msecs; break_Out_Of_This_Loop; } }
NSTimer
工作有点不同,比你想要的。 你需要的是你的计时器的计数器,以获得多less次循环。 如果你的计数器14(如果它是一个整数),你可以使其无效。
//start timer NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(play:) userInfo:nil repeats:YES]; //stop timer [timer invalidate];
你可以在没有这个的时候创build你的函数。
- (void)play { ...... ... counter++; //declare it in your header if(counter < 14){ x++; //your integer needs to be declared in your header to keep it's value } else { [timer invalidate]; } useValueofX; }
看看文档 。