iphone - 如何找到加载到 Malloc 32kb 中的漏水水龙头

标签 iphone objective-c memory-leaks avaudioplayer

我一直在与 Leaks 打交道,试图找出哪个函数没有被释放(我对此还是个新手)并且真的可以使用一些有经验的洞察力。

我有这段代码似乎是罪魁祸首。每次我按下调用此代码的按钮时,都会额外分配 32kb 的内存给内存,当释放按钮时,内存不会被释放。

我发现每次调用 AVAudioPlayer 播放 m4a 文件时,解析 m4a 文件的最终函数是 MP4BoxParser::Initialize() 而这个依次通过Cached_DataSource::ReadBytes

分配32kb内存

我的问题是,我该如何在它完成后重新分配它,以便它不会在每次按下按钮时都分配 32kb?

非常感谢您提供的任何帮助!

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

//stop playing
theAudio.stop;


// cancel any pending handleSingleTap messages 
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(handleSingleTap) object:nil];

UITouch* touch = [[event allTouches] anyObject]; 


NSString* filename = [g_AppsList objectAtIndex: [touch view].tag];

NSString *path = [[NSBundle mainBundle] pathForResource: filename ofType:@"m4a"];  
theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];  
theAudio.delegate = self; 
[theAudio prepareToPlay];
[theAudio setNumberOfLoops:-1];
[theAudio setVolume: g_Volume];
[theAudio play];
}

最佳答案

Cocoa 中内存管理的诀窍是平衡任何对 allocretaincopy 的调用与对 的后续调用>发布

在这种情况下,您将发送 alloc 来初始化您的 theAudio 变量,但您永远不会发送 release

假设您一次只播放一种声音,最好的方法是在您的 Controller 上设置一个属性(具有此 -touchesBegan 方法的 Controller )。属性声明如下所示:

@property (nonatomic, retain) AVAudioPlayer * theAudio;

然后您需要在 init 方法中将 theAudio 设置为 nil:

theAudio = nil; // note: simple assignment is preferable in init

并确保在您的dealloc 方法中释放变量:

[theAudio release];

现在,您的touchesBegan 可能如下所示:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    //stop playing
    theAudio.stop;
    ...
    AVAudioPlayer * newAudio = [[AVAudioPlayer alloc] initWithContentsOfUrl:...];
    self.theAudio = newAudio; // it is automatically retained here...

    theAudio.delegate = self; 
    [theAudio prepareToPlay];
    [theAudio setNumberOfLoops:-1];
    [theAudio setVolume: g_Volume];
    [theAudio play];

    [newAudio release];       // ...so you can safely release it here
}

关于iphone - 如何找到加载到 Malloc 32kb 中的漏水水龙头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2634523/

相关文章:

ios - 多文档绘图应用程序核心数据方法

iphone - <ApplicationName>_prefix.pch 文件的重要性

iphone - 在 iOS 网络调用中缓存?

objective-c - 使菜单项显示一个窗口

ios - UIWebView 从 NSString 加载 PDF 字节

Javascript:循环内存泄漏?

c++ - 如何修复/正确初始化/清理矩阵类泄漏内存

jQuery 内存泄漏与 DOM 删除

iphone - iPhone 应用程序的 POST REST-Web 服务调用

ios - 如何下载旧版本的 iPhone SDK?