I created a simple app to learn how to use NSWorkspaceWillSleepNotification and NSWorkspaceDidWakeNotification. My goal is to call a method when the computer sleeps and wakes. The app I created will change each label accordingly. After building the app, I launch it from my desktop. After the application is launched, I put the computer to sleep. When the computer wakes the labels in the application do not change. I added IBAction buttons to the window to make sure that the labels would change. When buttons are pressed the labels do indeed change. But I want something like this to happen automatically upon sleep and wake. What am I doing wrong?
#import "Controller.h"
@implementation Controller
- (void)fileNotifications {
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver: self
selector: @selector(makeSleep:)
name: NSWorkspaceWillSleepNotification
object: nil];
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver: self
selector: @selector(makeWake:)
name: NSWorkspaceDidWakeNotification
object: nil];
}
- (IBAction)makeSleep:(id)sender {
[sleepLabel setStringValue:@"Computer Slept!"];
}
- (IBAction)makeWake:(id)sender {
[wakeLabel setStringValue:@"Computer Woke!"];
}
@end
Instead of [[NSWorkspace sharedWorkspace] notificationCenter]
try using [NSNotificationCenter defaultCenter]
like this:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(makeSleep:)
NSWorkspaceWillSleepNotification
object:nil
];
and
[[NSNotificationCenter defaultCenter] addObserver:self
@selector(makeWake:)
NSWorkspaceDidWakeNotification
object:nil
];
The above is incorrect, see https://developer.apple.com/library/mac/qa/qa1340/_index.html
Using [[NSWorkspace sharedWorkspace] notificationCenter]
is necessary.
You should add observers upon - (void)awakeFromNib
method.