问题
I am currently working on an app that requires a sound file to be played at exact intervals, which are variable in duration.
I seem to remember being told that NSTimer simply places an operation onto the stack after the specified duration, rather than the operation being run after the specified duration. This would mean that if there were lots of other operations on the stack before it, it would not be called on time.
I would like to know if this is indeed correct, and if so, is there any way of getting an operation to be guaranteed to run after a specified duration.
Before any makes the comment that the sound files may be delayed the first time, they are already pre-loaded to avoid this.
回答1:
In the first paragraph of Apple's NSTimer documentation you'll find this:
A timer is not a real-time mechanism; it fires only when one of the run loop modes to which the timer has been added is running and able to check if the timer’s firing time has passed. Because of the various input sources a typical run loop manages, the effective resolution of the time interval for a timer is limited to on the order of 50-100 milliseconds. If a timer’s firing time occurs during a long callout or while the run loop is in a mode that is not monitoring the timer, the timer does not fire until the next time the run loop checks the timer. Therefore, the actual time at which the timer fires potentially can be a significant period of time after the scheduled firing time.
So you will definitely run (or play your sound, in your case) after your scheduled firing time, but not necessarily exactly at your time.
来源:https://stackoverflow.com/questions/11835023/nstimer-accuracy