2014-01-17 44 views
1

引用这是代码:崩溃`[NSApp表示运行]`当委托不再

@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],则会崩溃。

如果我没有设置委托,它不会崩溃。

如果我之前引用委托,它工作正常:

AppDelegate* appDelegate = [[AppDelegate alloc] init]; 
[NSApp setDelegate:appDelegate]; 

所以我想它会立即释放委托,因为ARC,也因为第一个版本的代表大概只有弱引用,对不对?但是,你应该如何做相同的代码呢?

+0

莫非你尝试按照这种方式设置委托:'[[NSApplication sharedApplication] setDelegate:self];' – divaka

+0

是否有任何理由不使用'NSApplicationMain(argc,(const char **)argv)'? – user3125367

+0

@ user3125367:是的(在我的情况下)。 – Albert

回答

4

是的,你猜对了,NSApplication不保留委托,(与ARC的弱引用)。 所以你可以建立与-fno-objc-arc的main.m文件与你当前的代码:

int main(int argc, char *argv[]) 
{ 
    @autoreleasepool 
    { 
     [NSApplication sharedApplication]; 
     [NSApp setDelegate:[[AppDelegate alloc] init]]; 
     [NSApp finishLaunching]; 
     [NSApp run]; 
    } 
} 

或设置你的appdelegate在main.m文件静态的,例如,与ARC建立

static AppDelegate* _appDelegate; 

int main(int argc, char *argv[]) 
{ 
    @autoreleasepool 
    { 
     _appDelegate = [[AppDelegate alloc] init]; 
     [NSApplication sharedApplication]; 
     [NSApp setDelegate:_appDelegate]; 
     [NSApp run]; 
    } 
}