由於面板是非阻塞的,所以一旦面板打開,代碼就會繼續執行。打開的面板正在被釋放,因爲你沒有在某個地方引用它。 -openPanel
是一個方便的構造函數,它返回一個autoreleased對象,噹噹前自動釋放池被彈出或者(當在GC應用程序中)下一次運行收集器時它將會消失。在你的情況下,這是你的方法完成後立即。
如果你想面板留下來,你必須明確使用-retain
保留它,並隨後-release
它在didEndSelector:
- (void)showPanel
{
NSOpenPanel *openPanel = [[NSOpenPanel openPanel] retain]; //note the retain
[openPanel beginForDirectory:nil
file:nil
types:[NSImage imageFileTypes]
modelessDelegate:self
didEndSelector:@selector(myOpenPanelDidEnd:returnCode:contextInfo:)
contextInfo:NULL];
}
- (void)myOpenPanelDidEnd:(NSOpenPanel *)panel returnCode:(int)returnCode contextInfo:(void*)contextInfo
{
NSArray* fileNames = [panel filenames];
[panel release];
//do something with fileNames
}
如果您使用垃圾收集,保留和釋放沒有-ops,因此您必須改爲存儲對NSOpenPanel
的強引用,例如將其存儲在實例變量中。