How to receive NSNotifications while manually using NSRunloop

499 views Asked by At

I can observe NSWorkspaceWillPowerOffNotification notifications in the application delegate of a GUI program, but not in a command line utility. Any ideas why the following does not work? Or is there a different approach I should consider?

Edit: Cold it be that NSWorkspace's notification center doesn't work for a GUI-less program? (I have verified that |notificationCenter| is not nil)

@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

There are 0 answers