【问题标题】:simple example, but I don't understand why there are no leaks简单的例子,但我不明白为什么没有泄漏
【发布时间】:2011-08-05 08:00:19
【问题描述】:
- (IBAction) btnFire:(id)sender {

    NSString *path = [NSString stringWithFormat:@"%@%@", [[NSBundle mainBundle] resourcePath],   @"/gunShot.wav"];

    NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];

    AVPlayer *shotSound = [[AVPlayer alloc] initWithURL:filePath];

    [shotSound play];
}

如果我在这里释放 shotSound,它就不会播放。同时没有泄漏。

为什么仪器显示没有泄漏?如何释放shotSound?

【问题讨论】:

    标签: iphone xcode memory-management


    【解决方案1】:

    当你按下按钮时你会一次又一次地需要声音,所以你应该在类级别声明它而不是每次都在按钮中初始化它,你可以在 viewDidLoad 方法中初始化它,或者你也可以这样做

    - (IBAction) btnFire:(id)sender {
    
     if(shotSound==nil)
    {
            NSString *path = [NSString stringWithFormat:@"%@%@", [[NSBundle mainBundle] resourcePath],   @"/gunShot.wav"];
    
            NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
    
           shotSound = [[AVPlayer alloc] initWithURL:filePath];
    }
    
            [shotSound play];
    
    }
    

    dealloc 中发布它。如果你只是想在这个动作上有声音,你可以使用AVAudioPlayer

    有时仪器的泄漏无法检测到,在这种情况下,您可以使用构建和分析工具。另外,正如您所说,如果您释放播放器对象,则应用程序崩溃可能是因为它仍在播放音频并且您释放了播放器(不确定)。

    【讨论】:

    • 这是正确答案。 shotSound 应该分配一次,然后在deallocviewDidUnload 中释放。我添加了viewDidUnload,因为当视图不存在时没有理由保留分配。 @Ravin 的代码会在需要时再次对其进行初始化。
    • 谢谢。你的意思是 shotSound 应该是 ivar 吗?
    • if (ivar--> instance variable) then yes :)
    【解决方案2】:

    你可以试试

    AVPlayer *shotSound = [AVPlayer playerWithURL:filePath];

    注意:这会返回一个新播放器来播放由给定 URL 引用的单个视听资源。

    【讨论】:

    • 这种方式有什么缺点吗?
    • 如果您只想播放单个文件,我认为这就足够了。当你这样做时,玩家会在 AutoReleasePool 耗尽时被释放
    猜你喜欢
    • 2020-03-10
    • 1970-01-01
    • 2012-05-03
    • 1970-01-01
    • 2010-11-08
    • 1970-01-01
    • 1970-01-01
    • 2011-03-05
    • 1970-01-01
    相关资源
    最近更新 更多