我试图在我的应用程序中的每个按钮上播放点击声音,因为我创建了一个实用程序类,它的.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];它工作得很好,我成功地演奏出了声音。当我分析代码时出现了问题。编译器显示,在实用程序类的initWithDefaultClickSoundName方法中存在内存泄漏,因为我将alloc方法发送到self.audioplayer,而不是释放它。
释放这个对象的最佳地点是什么?
发布于 2012-12-19 13:48:16
问题是当您分配对象--它的retainCount将是1 --时,您将该对象分配给retain属性对象。然后它将再次保留该对象,因此retainCount将为2。
retain属性的setter代码类似于:
- (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-19 13:49:06
self.audioplayer =[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:BS_path_blue] error:NULL];在这里,创建一个新对象,然后将其分配给保留的属性。但是,除了该属性之外,您没有对对象的引用,因此它会泄漏。你增加了两次保留数。
按优先顺序修正:
self.property = [[[Object alloc] init] autorelease];https://stackoverflow.com/questions/13953716
复制相似问题