当应用程序在 Lion 上失去焦点时,NSNotificationCenter Observer 停止接收事件

nba*_*lle 1 cocoa nsnotification nsnotificationcenter osx-lion

我有一个从默认 NSNotificationCenter 订阅特定类型通知的应用程序。

在 OSX Lion 上,它工作正常,只是当应用程序失去焦点(另一个应用程序变为活动状态)时,它会停止接收事件。当应用获得焦点时,它会再次开始接收事件。该应用程序在以前版本的 OSX 上没有这种行为,它总是收到通知,即使它不在焦点上。

我能做些什么来改变这种行为?

谢谢!弥敦道

Vip*_*ney 5

我知道回答这个有点晚了,仍然是为了我的记录,如果有人还在搜索。

我的 OS X 菜单栏应用程序有同样的问题。我希望该应用程序能够观察所有状态。

原因:

当应用失去焦点时,观察者被暂停。

IE。当应用程序变为非活动状态时,它会调用该方法

-(void)applicationDidResignActive:(NSNotification *)notification
Run Code Online (Sandbox Code Playgroud)

默认情况下 NSDistributedNotificationCenter 对象被挂起。

解决方案:我为 NSDistributedNotificationCenter 创建了一个对象

NSDistributedNotificationCenter *center=[NSDistributedNotificationCenter defaultCenter];
Run Code Online (Sandbox Code Playgroud)

然后当应用程序失去焦点时,它会调用applicationDidResignActive方法,并在其中通过向setSuspended 方法发送NO使 NSDistributedNotificationCenter 对象从挂起状态恢复。

-(void)applicationDidResignActive:(NSNotification *)notification
{
    [center setSuspended:NO];
}
Run Code Online (Sandbox Code Playgroud)

然后即使失去焦点,应用程序也会开始观察。


mas*_*ash 5

根据NSDistributionNotificationCenter参考 https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDistributedNotificationCenter_Class/Reference/Reference.html#//apple_ref/doc/uid/20000396-BCICEHHB

当应用程序不活动时,NSApplication 类会自动暂停分布式通知传递。基于Application Kit框架的应用程序应该让AppKit管理通知传递的暂停。仅基础项目可能偶尔需要使用此方法。

你可以

设置观察者在挂起时的NSNotificationSuspensionBehaviorDeliverImmediately行为

- (void)addObserver:(id)notificationObserver selector:(SEL)notificationSelector name:(NSString *)notificationName object:(NSString *)notificationSender suspensionBehavior:(NSNotificationSuspensionBehavior)suspendedDeliveryBehavior
Run Code Online (Sandbox Code Playgroud)

deliverImmediately在发布时设置为 YES

- (void)postNotificationName:(NSString *)notificationName object:(NSString *)notificationSender userInfo:(NSDictionary *)userInfo deliverImmediately:(BOOL)deliverImmediately
Run Code Online (Sandbox Code Playgroud)

在暂停状态下立即发送通知。

并确保你没有定期杀死distnoted. 我忘记了我有一个旧的启动代理脚本来killall distnoted避免内存泄漏。