1

I am wrapping AVAudioPlayer with a very simple class that allows me to specify and url and immediately play it and then call a completion block, like this:

[AudioPlayer playAudioWithURL:url
                  completionBlock:^{
                      //finished playing
                  }];

Reason why I wrote this is because it's very easy, simple. No need to implement delegate, etc...Problem is, this won't work. Doing this in a function will obviously allocate it on stack and it will be de-allocated soon, causing the sound to stop playing.

So, what's the best way to implement this kind of wrapper, to keep a reference around until the sound is finished playing? Thanks

4

2 回答 2

0

You should not have any problem. What makes you think that it "will obviously allocate it on stack and it will be de-allocated soon"? Have you tried it? You obviously don't have a good understanding of how memory management in Objective-C works.

In your implementation of playAudioWithURL:urlcompletionBlock:, you will inevitably have some kind of asynchronous dispatch. This dispatch will inevitably have to retain your audio player object, in order to have it play stuff. So no, it won't get deallocated, unless you are doing something wrong.

于 2012-11-21T08:37:46.220 回答
-1

我不确定这将如何使用 ARC,因为您无法真正管理保留/释放周期。我已经使用包装器做了类似的事情UIAlertView,而我所做的——当然不使用 ARC——只是在方法[self retain]期间调用包装器类show,然后在调用委托方法时在包装器上,调用completionBlockand then [self release]。这保证了(只要您遵循保留/释放规则!)包装类将至少在调用回调之前保持活动状态,并且在通常情况下,一旦完成工作,包装器就会自行自杀。同样,由于您无法使用 ARC 管理保留周期,我不确定这是否可行。

您的替代方法可能是研究简单的子类AVAudioPlayer化或创建它的类别版本,将委托设置为自身。这可能能够让它存活足够长的时间,让它持续到完整的声音播放——尽管我对 ARC 的工作原理有点模糊。

祝你好运!

于 2012-08-28T12:40:56.223 回答