views:

117

answers:

2

Hi

I have to start more than one processes simultaneously - an AVAudioPlayer's play, a timer and a file write operation.

If I just write them in a method, they are executed one after the other and the start of all the operations has a slight lag.

Any ideas? Appreciate any help.

Thanks.

+2  A: 

Why don't you use threads?

You can do it easily by using:

- (void)performSelectorInBackground:(SEL)aSelector withObject:(id)arg

or by using NSOperation with a NSOperationQueue.

Have a look at this question for more details.

Notes:

  • you'll need an autorelease pool in your thread if you use any autoreleased classes
  • if you want to use a timer in another thread you'll also need another runloop.
  • watch out for thread safetiness. For instance, I don't know if AVAudioPlayer can be used on a thread different from the main thread.
  • I don't think you can schedule a NSTimer from within a NSOperation
Jean Regisser
If you are doing this once only, performSelectorInBackground is the simplest code. However if you do it a lot it is not optimal. I would suggest the NSOperation route.
Roger Nolan
Thanks a lot guys.
lostInTransit
+1  A: 

Adding too much concurrency could be the wrong approach here. You might want to investigate setting up the timer and playing the audio file on the main thread while performing the blocking file write call on a background thread. The important concept here is to stay away from blocking calls on the main thread, especially when you're dealing with file or network I/O.

You'll want to avoid creating too many extra threads as the iPhone is a single-CPU device, and multiple threads will cause more resource consumption.