Search code examples
objective-cosx-snow-leopard

Knowing when the system has gone to sleep in a Menu Extra?


I developed a Menu Extra (menulet) for the Mac but I'd like to know if the machine using the Menu Extra has gone to sleep. I implemented a snooze function but since it's a time-based method it's rather unreliable. Any hints or advice would be greatly appreciated!

Thanks!


Solution

  • You probably want to check out NSWorkspaceWillSleepNotification in NSWorkspace.
    The trick is, you need to register for the notifications on NSWorkspace's notificationCenter, not the default one. See Technical Q&A QA1340.

    Sample code:

    - (void) receiveSleepNote: (NSNotification*) note
    {
        NSLog(@"receiveSleepNote: %@", [note name]);
    }
    
    - (void) fileNotifications
    {
        // These notifications are filed on NSWorkspace's notification center, not the default 
        // notification center. You will not receive sleep/wake notifications if you file 
        // with the default notification center.
        [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self 
                selector:@selector(receiveSleepNote:) 
                name: NSWorkspaceWillSleepNotification object:nil];
    }