【问题标题】:ShowModalWindow in Objective-C would cause memory leak with GC on?Objective-C 中的 ShowModalWindow 会在 GC 开启时导致内存泄漏?
【发布时间】:2011-03-18 15:25:30
【问题描述】:

我的应用在 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

【问题讨论】:

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


    【解决方案1】:

    泄漏实际上是在那一行之上的一行:

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

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

    【讨论】:

    • 感谢您的回复。应用项目开启了垃圾回收,那么WindowController会被垃圾回收吗?那是我从GC手册上读到的,release,autorelease在GC开启的时候就没用了。
    猜你喜欢
    • 2017-02-20
    • 1970-01-01
    • 2015-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-03
    • 1970-01-01
    相关资源
    最近更新 更多