2

I'm nearing the end of a big iPhone project and whilst checking for memory leaks stumbled on this huge one. I implemented the sound following this tutorial:

http://www.gehacktes.net/2009/03/iphone-programming-part-6-multiple-sounds-with-openal/

Works a charm, a lot of people use it but I get a huge leak a start of the project when sound is initially loaded in. Below are the lines of code that start of the leak:

[[Audio sharedMyOpenAL] loadSoundWithKey:@"music" File:@"Music" Ext:@"wav" Loop:true];
[[Audio sharedMyOpenAL] loadSoundWithKey:@"btnPress" File:@"BtnPress" Ext:@"wav" Loop:false];
[[Audio sharedMyOpenAL] loadSoundWithKey:@"ting1" File:@"GlassTing1" Ext:@"wav" Loop:false];

etc. etc. it loads in 20 sounds altogether. And more specifically in the Audio.m file this chunk of code:

+ (Audio*)sharedMyOpenAL {

@synchronized(self) {
    if (sharedMyOpenAL == nil) {
        sharedMyOpenAL = [[self alloc] init]; // assignment not done here

    }
}
return sharedMyOpenAL;
}

I am unsure how to resolve this and any help on the matter would be greatly appreciated.

Thanks.

4

1 回答 1

2

“泄漏”不就是Audio单例吗?我不确定泄漏检测是如何工作的,但从某种角度来看,大多数单例都是泄漏,因为它们仅在您的应用程序退出后才释放内存。

如果真的是这样,那就看你是否需要释放声音使用的内存了。内存使用量不应该增加,因此您不必担心“传统泄漏”场景,即您的应用程序会占用越来越多的内存,直到它被杀死。您使用的代码似乎不支持声音卸载,因此如果您想释放内存,则必须自己添加该代码。

以及个人观点:使用单例编写音效引擎并不是一个好的设计。管理声音变得很痛苦(这正是您面临的问题),单例添加了许多不必要的样板代码等。我认为声音不应该是具有自己生命周期的简单独立对象,这就是方式我在尝试使用 OpenAL SFX 引擎时已经做到了。当然,我可能是错的。


更新:我想神奇的“这里没有完成任务”是关键。单例代码取自Apple 文档,但有人插入了一个额外的任务。该sharedFoo方法应如下所示:

+ (MyGizmoClass*)sharedManager
{
    @synchronized(self) {
        if (sharedGizmoManager == nil) {
            [[self alloc] init]; // assignment not done here
        }
    }
    return sharedGizmoManager;
}

当您对 执行额外的分配时self,您会创建您正在寻找的泄漏。

于 2009-10-13T08:34:55.363 回答