在以下情况下出现MemoryLeak问题 [英] MemoryLeak problem in following case
问题描述
单击播放按钮时出现内存泄漏....
I am getting a memory leak when i click the play button....
我正在模拟器上运行和性能工具" ...下使用泄漏"工具进行测试
I am testing with that "Leak" tool under "Run and performance tool"....on simulator
当我第一次单击播放按钮时,我正在泄漏....
I am getting that leak when i click the play button first time.....
这是我的代码....
-(IBAction)play
{
[self setPlayer];
[self playme];
}
-(IBAction)stop
{
[self stopme];
[self releasePlayer];
}
-(void)setPlayer
{
NSURL *file = [[NSURL alloc] initFileURLWithPath:
[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"shut up.mp3"]];
NSError *err = nil;
player = [[AVAudioPlayer alloc] initWithContentsOfURL:file error:&err];
[file release];
player.numberOfLoops = -1;
[player prepareToPlay];
player.volume=1.0;
}
-(void)playme
{
if (!isPlaying)
{
[player play];
isPlaying=YES;
}
}
-(void)stopme
{
if (isPlaying)
{
[player stop];
isPlaying=NO;
}
}
-(void)releasePlayer
{
if(!isPlaying)
{
[player release];
player=nil;
}
isPlaying=NO;
}
推荐答案
我认为,以下语句是内存泄漏的根源,
I think, the below statement is the source of memory leak,
player = [[AVAudioPlayer alloc] initWithContentsOfURL:file error:&err];
以下是讨论相同问题的SO帖子.
Here is the SO posts which has discussed the same issue.
这是博客文章
已编辑
根据博客教程,您的代码必须如下所示.
As per the blog tutorial your code must be look like below.
-(void)setPlayer
{
NSURL *file = [[NSURL alloc] initFileURLWithPath:
[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"shut up.mp3"]];
NSError *err = nil;
NSData *data = [NSData dataWithContentsOfFile:file];
AVAudioPlayer *player = [AVAudioPlayer alloc];
if([player initWithData:audioData error:NULL])
{
player.numberOfLoops = -1;
[player prepareToPlay];
player.volume=1.0;
[player autorelease];
}
else
{
[player release];
player = nil;
}
[file release];
}
无泄漏版本存储alloc返回的指针,而不是initWithData:error:返回的指针.这样,无论发生什么情况,播放器仍然可以释放.
The leak-free version stores the pointer returned by alloc, rather than the pointer returned by initWithData:error:. That way, whatever happens, the player can still be released.
这篇关于在以下情况下出现MemoryLeak问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!