gpt4 book ai didi

iphone - 保留属性时内存泄漏

转载 作者:可可西里 更新时间:2023-11-01 04:47:46 24 4
gpt4 key购买 nike

我试图在我的应用程序中的每个按钮点击时播放点击声音为此,我创建了一个 Utility 类,其 .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

然后在按钮上点击我正在做的任何类(class)

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

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

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

最佳答案

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

保留属性的 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];

关于iphone - 保留属性时内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13953716/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com