我正在尝试在我的应用程序中的每个按钮单击时播放单击声音为此我创建了一个实用程序类,其 .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并且不释放它。
释放此对象的最佳位置是什么?