如何在手动使用NSRunloop时接收NSNotifications

时间:2013-12-06 16:12:53

标签: cocoa nsnotificationcenter nsrunloop

我可以在GUI程序的应用程序委托中观察NSWorkspaceWillPowerOffNotification通知,但不能在命令行实用程序中观察。任何想法为什么以下不起作用?或者我应该考虑采用不同的方法吗?

编辑:冷酷的是,NSWorkspace的通知中心不适用于无GUI的程序吗? (我已经确认| notificationCenter |不是零)

@interface Helper : NSObject
-(void)userLogout:(NSNotification*)notification;
@end

@implementation Helper
-(void)userLogout:(NSNotification*)notification
{
    NSLog(@"Notification Received");
}
@end

int main(int argc, const char * argv[])
{
    @autoreleasepool {
        Helper* helper = [[Helper alloc] init];

        NSNotificationCenter* notificationCenter = [[NSWorkspace sharedWorkspace] notificationCenter];
        [notificationCenter addObserver:helper
                               selector:@selector(userLogout:)
                                   name:NSWorkspaceWillPowerOffNotification
                                 object:nil];

        NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
        [runLoop run];
    }
    return 0;
}

0 个答案:

没有答案