保留财产时内存泄漏

时间:2012-12-19 13:42:47

标签: iphone ios memory-management

我正试图在我的应用中点击每个按钮时发出咔嗒声 为此,我创建了一个实用工具类,其.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 而不释放它。

发布此对象的最佳位置是什么?

2 个答案:

答案 0 :(得分:2)

问题是,当您分配对象时,它的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];

答案 1 :(得分: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];