メソッドを有効にするには、NSWorkSpacedIdWakeNotificationを使用してください。
-
15-11-2019 - |
質問
NSWorkSpaceWillsLeepNotificationとNSWorkSpacedIdwakenotificationを使用する方法を学ぶための簡単なアプリを作成しました。私の目標は、コンピュータが眠って目を覚ますときにメソッドを呼び出すことです。私が作成したアプリはそれに応じて各ラベルを変更します。アプリを構築した後、私は自分のデスクトップからそれを起動します。アプリケーションが起動された後、私はコンピュータをスリープさせます。コンピュータがアプリケーション内のラベルを起動すると変わりません。ラベルが変更されるように、ウィンドウにIBACTIONボタンを追加しました。ボタンが押されたら、ラベルは確かに変更されます。しかし、私はこのようなものが睡眠と覚醒時に自動的に起こるようにしたいです。私は何を間違っていますか?
#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.