由于面板是非阻塞的,因此一旦面板打开,代码就会继续执行。正在释放打开的面板,因为您没有在某处持有对它的引用。-openPanel
是一个方便的构造函数,并返回一个自动释放对象,当当前自动释放池被弹出或(在 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
}
如果您使用垃圾收集,则保留和释放是无操作的,因此您必须存储对 的强引用NSOpenPanel
,例如将其存储在实例变量中。