这是我的代码模板:
int main(int argc, char *argv[]) {
// create an autorelease pool
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
// make sure the application singleton has been instantiated
NSApplication * application = [NSApplication sharedApplication];
// instantiate our application delegate
AppDelegate * applicationDelegate =
[[[AppDelegate alloc] init] autorelease];
// assign our delegate to the NSApplication
[application setDelegate:applicationDelegate];
// call the run method of our application
[application run];
// drain the autorelease pool
[pool drain];
// execution never gets here ..
return 0;
}
“[pool drain]”后跟“return 0”,为什么永远不会被执行。
但是,我发现了另一个gnustep官方例子,它做了同样的事情。
int
main(int argc, char **argv, char** env)
{
id pool = [NSAutoreleasePool new];
NSApplication *theApp;
#if LIB_FOUNDATION_LIBRARY
[NSProcessInfo initializeWithArguments:argv count:argc environment:env];
#endif
theApp = [NSApplication sharedApplication];
[theApp setDelegate: [browserController new]];
[theApp run];
[pool release];
return 0;
}
要证明它“[theApp run]”永远不会回来,我已经完成了在“[theApp run]”之后立即添加无限循环的做法。但它永远不会被执行。为什么GNUSTEP官方的例子会这样做?
答案 0 :(得分:4)
您确定[pool drain]
实际上也被调用了吗?除非调用[application run]
,否则[NSApp stop]
将无法返回(这很少见)。如果调用更常见的[NSApp terminate]
,则为the docs say:
不要费心将最终的清理代码放在应用程序的main()中 功能 - 它永远不会被执行。如果需要清理,请执行 委托的applicationWillTerminate:方法中的清理。
将申请交给run
后,您通常无法取回申请。