简体   繁体   中英

ShowModalWindow in Objective-C would cause memory leak with GC on?

My app is running with GC turned on.

Instrument Leak always tell me that this line of code has 100% memory leak:

[NSApp runModalForWindow:[theWindowController window]];

I have no idea why.

And here is the whole app code:

/* delegate */

#import "m_ModalWindowAppDelegate.h"
#import "modalWindowController.h"

@implementation m_ModalWindowAppDelegate

@synthesize window;

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    // Insert code here to initialize your application 
}

- (IBAction) openModalWindowButtonClicked: (id) sender
{
    modalWindowController *theWindowController = [[modalWindowController alloc] init];

    [NSApp runModalForWindow:[theWindowController window]];
    [NSApp endSheet: [theWindowController window]];
    [[theWindowController window] orderOut:self];
}

@end


/* modalWindowController */

#import "modalWindowController.h"


@implementation modalWindowController

- (id) init
{
    self = [self initWithWindowNibName:@"modalWindow"];

    return self;
}


- (IBAction) closeButtonClicked:(id)sender
{
    [NSApp stopModal];
}

@end

The leak is actually one line above that one:

modalWindowController *theWindowController = [[modalWindowController alloc] init];

You're allocating a modalWindowController and assigning it to a local pointer. When the method ends, the pointer goes out of scope but you never release the object that you allocated. At that point, you no longer have a way to refer to the object (no more pointer), so you can't release it in the future. This is a leak.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM