保留财产时内存泄漏

abd*_*.me 5 iphone memory-management ios

我试图在我的应用程序中的每个按钮单击时发出咔嗒声为此我创建了一个实用工具类,其.h和.m如下

.h文件

@interface SoundPlayUtil : NSObject<AVAudioPlayerDelegate,AVAudioSessionDelegate>
{
    AVAudioPlayer *audioplayer;   
}
@property (retain, nonatomic) AVAudioPlayer *audioplayer;
-(id)initWithDefaultClickSoundName;
-(void)playIfSoundisEnabled;
@end
Run Code Online (Sandbox Code Playgroud)

.m文件

@implementation SoundPlayUtil
@synthesize audioplayer;

-(id)initWithDefaultClickSoundName
{
self = [super init];
    if (self)
{
    NSString* BS_path_blue=[[NSBundle mainBundle]pathForResource:@"click"   ofType:@"mp3"];
    self.audioplayer =[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:BS_path_blue]  error:NULL];
   [self.audioplayer prepareToPlay];
}
return self;
}

-(void)playIfSoundisEnabled
{
if ([[NSUserDefaults standardUserDefaults] boolForKey:soundStatus]==YES)
{
    [self.audioplayer play];
}
}

-(void)dealloc
{
[audioplayer release];
[super dealloc];
}
@end
Run Code Online (Sandbox Code Playgroud)

然后按钮点击我正在做的任何课程

 SoundPlayUtil *obj = [[SoundPlayUtil alloc] initWithDefaultClickSoundName];
 [obj playIfSoundisEnabled];
 [obj release];
Run Code Online (Sandbox Code Playgroud)

它工作正常,我成功播放声音.当我分析代码时出现问题.编译器显示实用程序类的.m 中的initWithDefaultClickSoundName方法中存在内存泄漏,因为我正在向self.audioplayer发送alloc方法而不释放它.

释放此物体的最佳位置是什么?

Mid*_* MP 2

问题是,当您分配对象时,它的保留计数将为 1,您正在将该对象分配给保留属性对象。然后它会再次保留该对象,因此保留计数将为 2。

保留属性的 setter 代码类似于:

- (void)setAudioplayer: (id)newValue
{
    if (audioplayer != newValue)
    {
        [audioplayer release];
        audioplayer = newValue;
        [audioplayer retain];
    }
}
Run Code Online (Sandbox Code Playgroud)

更改:

self.audioplayer =[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:BS_path_blue]  error:NULL];
Run Code Online (Sandbox Code Playgroud)

喜欢;

self.audioplayer =[[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:BS_path_blue]  error:NULL] autorelease];
Run Code Online (Sandbox Code Playgroud)

或类似:

 AVAudioPlayer *player = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:BS_path_blue]  error:NULL];
 self.audioplayer = player;
 [player release];
Run Code Online (Sandbox Code Playgroud)