Utilisez NsworkspaceDidDidIndification pour activer la méthode?
-
15-11-2019 - |
Question
J'ai créé une application simple pour apprendre à utiliser NsworkspaceWillsleepnotification et NsworkSpaceDidDidDuewakenotification.Mon objectif est d'appeler une méthode lorsque l'ordinateur dort et se réveille.L'application que j'ai créée changera chaque étiquette en conséquence.Après la construction de l'application, je le lance de mon bureau.Une fois l'application lancée, je mets l'ordinateur dormir.Lorsque l'ordinateur se réveille, les étiquettes de l'application ne changent pas.J'ai ajouté des boutons d'ibaction à la fenêtre pour vous assurer que les étiquettes changeraient.Lorsque les boutons sont enfoncés, les étiquettes changent effectivement.Mais je veux quelque chose comme ça se produise automatiquement au sommeil et à la réveil.Qu'est-ce que je fais mal?
#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
La solution
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.