5

我正在尝试在我的应用程序中的每个按钮单击时播放单击声音为此我创建了一个实用程序类,其 .h 和 .m 如下

.h 文件

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

.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

并在按钮上单击我正在做的任何课程

 SoundPlayUtil *obj = [[SoundPlayUtil alloc] initWithDefaultClickSoundName];
 [obj playIfSoundisEnabled];
 [obj release];

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

释放此对象的最佳位置是什么?

4

2 回答 2

2

问题是当您分配对象时,它的 retainCount 将为 1,您将该对象分配给一个保留属性对象。然后它将再次保留对象,因此retainCount 将为2。

保留属性的设置器代码类似于:

- (void)setAudioplayer: (id)newValue
{
    if (audioplayer != newValue)
    {
        [audioplayer release];
        audioplayer = newValue;
        [audioplayer retain];
    }
}

更改:

self.audioplayer =[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:BS_path_blue]  error:NULL];

喜欢;

self.audioplayer =[[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:BS_path_blue]  error:NULL] autorelease];

或喜欢:

 AVAudioPlayer *player = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:BS_path_blue]  error:NULL];
 self.audioplayer = player;
 [player release];
于 2012-12-19T13:48:16.170 回答
0
self.audioplayer =[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:BS_path_blue]  error:NULL];

在这里,您创建一个新对象,然后将其分配给保留属性。但是,除了属性之外,您没有再次引用该对象,因此它会泄漏。您已将保留计数增加了两次。

要修复,按优先顺序:

  1. 转换为 ARC ;)
  2. 创建一个局部变量,将其分配给属性,然后释放它。

    Object *object = [[Object alloc] init];
    self.property = object;
    [object release];
    
  3. 在添加对象时向对象添加自动释放调用:self.property = [[[Object alloc] init] autorelease];

于 2012-12-19T13:49:06.383 回答