Most likely to be on-time: +timeWithTimeInterval or -performSelector:withObject:afterDelay:

StackOverflow https://stackoverflow.com/questions/1746826

  •  20-09-2019
  •  | 
  •  

Question

I would like to play a sound for only a short span of time, shorter than the duration of the sound file. Therefore, at the same time as I start playing, I would like to queue up a task that will stop the sound.

I see two choices for queuing up the stop method: NSTimer and performSelector:withObject:afterDelay:

Does anyone know which of the two is most likely to trigger on time, or have a higher priority? It is not imperative that I get called with millisecond accuracy, but accuracy to 0.1 second would be great.


Addendum: Does anyone know where I could find documentation on the priority of different timer and delay tasks? For example, how would the below rank:

  • NSTimer tasks
  • performSelector
  • the calling of a view's drawRect after setNeedsDisplay has been called
  • the calling of a layer's drawing routines after setNeedsDisplay has been called
  • any other delayed tasks

And would it be useful to try to do this in a different thread?

Was it helpful?

Solution

performSelector:withObject:afterDelay: will create a timer to know when to fire so both approaches should be equally (un-)reliable. If your code performs an expensive calculation on the main thread and doesn't return control to the run loop or if the run loop has to process lots of events, the timer won't fire on time.

OTHER TIPS

Have a NSTimer, but with a much smaller time interval than the one that your sound has to play. When your timer fires, and that is a couple of times while your sound plays, you would count how much time has passed since you started it. When that time exceeds a margin set by you, you stop the sound.

From my understanding, they should be pretty much the same. However, the best way to figure this out is to test it yourself. Run a bunch of tests and record the exact time, then see which is closer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top