Objective-C中的ShowModalWindow会导致内存泄漏吗?

时间:2011-03-18 15:25:31

标签: objective-c memory-leaks garbage-collection

我的应用程序在GC打开的情况下运行。

Instrument Leak总是告诉我这行代码有100%的内存泄漏:

[NSApp runModalForWindow:[theWindowController window]];

我不知道为什么。

以下是整个应用代码:

/* 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

1 个答案:

答案 0 :(得分:0)

泄漏实际上比那一行高一行:

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

您正在分配modalWindowController并将其分配给本地指针。当方法结束时,指针超出范围,但您永远不会释放您分配的对象。此时,您无法再引用该对象(不再有指针),因此将来无法释放它。这是泄密。