这是代码:
@interface AppDelegate : NSObject <NSApplicationDelegate>
@end
@implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
printf("My app delegate: finish launching\n");
}
@end
int main(int argc, char *argv[])
{
@autoreleasepool
{
[NSApplication sharedApplication];
[NSApp setDelegate:[[AppDelegate alloc] init]];
[NSApp run];
}
}
它在[NSApp run]
中崩溃,但我并没有真正看到我错过了什么。如果我在 run
之前添加 [NSApp finishLaunching]
,它就会在那里崩溃。
如果我不设置委托(delegate),它就不会崩溃。
如果我之前引用委托(delegate),它工作正常:
AppDelegate* appDelegate = [[AppDelegate alloc] init];
[NSApp setDelegate:appDelegate];
所以我猜它会在第一个版本中立即释放委托(delegate),因为 ARC 并且因为委托(delegate)可能只是一个弱引用,对吧?但是,否则你应该如何执行相同的代码呢?
最佳答案
是的,你猜对了,NSApplication
不保留委托(delegate)(ARC的弱引用)。
因此,您可以使用当前代码使用 -fno-objc-arc
构建 main.m 文件:
int main(int argc, char *argv[])
{
@autoreleasepool
{
[NSApplication sharedApplication];
[NSApp setDelegate:[[AppDelegate alloc] init]];
[NSApp finishLaunching];
[NSApp run];
}
}
或者例如在 main.m 中将 AppDelegate 设置为静态,并使用 ARC 进行构建
static AppDelegate* _appDelegate;
int main(int argc, char *argv[])
{
@autoreleasepool
{
_appDelegate = [[AppDelegate alloc] init];
[NSApplication sharedApplication];
[NSApp setDelegate:_appDelegate];
[NSApp run];
}
}
关于objective-c - 当委托(delegate)不再被引用时,在 `[NSApp run]` 处崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21189168/