My program has a memory leak

前端 未结 5 2028
孤独总比滥情好
孤独总比滥情好 2021-01-16 22:17
-(IBAction)play2;

{
    CFBundleRef mainBundle = CFBundleGetMainBundle();
    CFURLRef soundFileURLRef;
    soundFileURLRef =CFBundleCopyResourceURL(mainBundle, 
           


        
5条回答
  •  情书的邮戳
    2021-01-16 22:54

    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.

    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.

    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);
    }
    

提交回复
热议问题