我的程序有内存泄漏 [英] My program has a memory leak

查看:166
本文介绍了我的程序有内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

-(IBAction)play2;

{
    CFBundleRef mainBundle = CFBundleGetMainBundle();
    CFURLRef soundFileURLRef;
    soundFileURLRef =CFBundleCopyResourceURL(mainBundle, 
                                             (CFStringRef) @"Bear3", CFSTR ("wav"), NULL);

    UInt32 soundID;
    AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID);
    AudioServicesPlaySystemSound(soundID);
}

这给了我一个错误:

potential leak of an object allocated " CFBundleResourceURL
returns a Core Foundation object with a +1 retain count


推荐答案

CFBundleCopyResourceURL 创建 CFURLRef 你拥有的对象,所以你需要在某些时候放弃使用 CFRelease 来放弃这个对象的所有权。同样你也会需要通过对 AudioServicesDisposeSystemSoundID 的另一次调用来平衡对 AudioServicesCreateSystemSoundID 的调用。

CFBundleCopyResourceURL creates a CFURLRef object that you own, so you need to relinquish ownership of this object at some point with CFRelease. Similarly you will need to balance your call to AudioServicesCreateSystemSoundID with another call to AudioServicesDisposeSystemSoundID.

对于Core Foundation,在其名称中包含单词创建复制的函数会返回一个对象拥有它,所以你必须放弃它的所有权。有关Core Foundation内存管理的更多信息,请参阅核心基础内存管理编程指南

For Core Foundation, functions that have the word Create or Copy in their name return an object that you own, so you must relinquish ownership of it when you are done with it. For more information about Core Foundation memory management, see the Core Foundation Memory Management Programming Guide.

只是为了给你一个提示,我可能会像这样处理内存管理(虽然我还没有编写Objective-C一段时间)。这也假设您希望保留URL引用,无论出于何种原因:

Just to give you a hint, I would probably handle the memory management like this (although I haven't coded Objective-C for a while). This also assumes you want to keep the URL reference for whatever reason:

@interface MyClass
{
    CFURLRef soundFileURLRef;
    UInt32 soundID;
}

@end

@implementation MyClass

- (id) init
{
    self = [super init];
    if (!self) return nil;

    CFBundleRef mainBundle = CFBundleGetMainBundle();

    soundFileURLRef = CFBundleCopyResourceURL(mainBundle, CFSTR("Bear3"), CFSTR("wav"));

    AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID);

    return self;
}

- (void) dealloc
{
    AudioServicesDisposeSystemSoundID(soundID);
    CFRelease(soundFileURLRef);
    [super dealloc];
}

- (IBAction) play2
{
    AudioServicesPlaySystemSound(soundID);
}

这篇关于我的程序有内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆