【问题标题】:Use NSWorkspaceDidWakeNotification to activate method?使用 NSWorkspaceDidWakeNotification 激活方法?
【发布时间】:2012-03-20 05:39:37
【问题描述】:

我创建了一个简单的应用程序来学习如何使用 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

【问题讨论】:

  • 虽然您的代码很可能不会崩溃,但您应该使用- (void)makeSleep:(NSNotification *)notification; 而不是- (IBAction)makeSleep:(id)sender。因为通知观察回调方法的用途与 IBActions 完全不同。之所以可行,仅仅是因为它们共享相同的选择器模式(即具有单个 id/object 参数的方法)。

标签: objective-c cocoa sleep wakeup nsworkspace


【解决方案1】:

尝试使用[NSNotificationCenter defaultCenter]代替[[NSWorkspace sharedWorkspace] notificationCenter]

像这样:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(makeSleep:) NSWorkspaceWillSleepNotification object:nil ];

[[NSNotificationCenter defaultCenter] addObserver:self @selector(makeWake:) NSWorkspaceDidWakeNotification object:nil ];

以上不正确,见https://developer.apple.com/library/mac/qa/qa1340/_index.html

使用[[NSWorkspace sharedWorkspace] notificationCenter] 是必要的。

您应该在- (void)awakeFromNib 方法上添加观察者。

【讨论】:

  • 好吧,我的问题是我需要将NSWorkspace 放入awakeFromNib 方法中。现在一切正常。感谢您的提示。我不需要更改任何其他内容。
  • 注册唤醒和睡眠通知时,绝对应该使用共享工作区的通知中心。由于您的答案已被接受,因此您应该对其进行编辑,以免混淆其他寻求帮助的人。
  • 这是完全错误的。 Apple 网站上的开发人员示例中明确指出,应该使用 NSWorkspace 通知中心,而不是这些通知的默认中心。见developer.apple.com/library/mac/qa/qa1340/_index.html
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-10
  • 1970-01-01
  • 1970-01-01
  • 2018-01-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多